在矩阵中的每两列上操作

时间:2016-03-19 20:53:46

标签: r loops matrix

Q1=c(0,1,0,1,0,1,0,1)
Q2=c(1,0,0,0,1,1,1,0)
Q3=c(0,0,0,0,0,0,0,0)
Q4=c(1,0,0,0,1,1,1,0)
Q = cbind(Q1,Q2, Q3, Q4)
Q = matrix(Q, 8, 4)

     [,1] [,2] [,3] [,4]
[1,]    0    1    0    1
[2,]    1    0    0    0
[3,]    0    0    0    0
[4,]    1    0    0    0
[5,]    0    1    0    1
[6,]    1    1    0    1
[7,]    0    1    0    1
[8,]    1    0    0    0

我想写一个函数

ifelse(Q[1]==1||Q[2]==1, 1,0)

然后继续增加第3列和第4列

ifelse(Q[3]==1||Q[4]==1, 1,0)

返回矩阵

这是我的代码:

n = function(n){
x <- matrix(n row= 8,n col=n)
for(i in 1:n){
  for (j in 1: 4){
i = 1
j = 1 
x[,i]= apply(Q, 1, function(x)if else(x[j]==1||x[j+1]==1, 1,0))
j = j+2
}
return(x)
}
}
n(1)
n(2)

     [,1] [,2]
[1,]    1   NA
[2,]    1   NA
[3,]    0   NA
[4,]    1   NA
[5,]    1   NA
[6,]    1   NA
[7,]    1   NA

我认为我做错了,新矩阵假设,加上我有超过100列,所以我必须每2列写一次增加循环

      [,1] [,2]
[1,]    1   1
[2,]    1   0
[3,]    0   0
[4,]    1   0
[5,]    1   1
[6,]    1   1
[7,]    1   1

1 个答案:

答案 0 :(得分:0)

谢谢你们,现在这次我做对了。我们可以根据您想要的变量进行分组。我有2种方法可以做到这一点,第一种方法不好,第二种方法更好

> Q1=c(0,1,0,1,0,1,0,1)
> Q2=c(1,0,0,0,1,1,1,0)
> Q3=c(0,0,0,0,0,0,0,0)
> Q4=c(1,0,0,0,1,1,1,0)
> Q5=c(1,0,0,0,1,1,1,0)
> Q6=c(0,0,0,0,0,0,0,0)
> Q7=c(1,0,0,0,1,1,1,0)
> Q8=c(0,0,0,0,0,0,0,0)
> Q9=c(1,0,0,0,1,1,1,0)
> Q = cbind(Q1,Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9)
> Q = matrix(Q, 8, 9)
> Q
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,]    0    1    0    1    1    0    1    0    1
[2,]    1    0    0    0    0    0    0    0    0
[3,]    0    0    0    0    0    0    0    0    0
[4,]    1    0    0    0    0    0    0    0    0
[5,]    0    1    0    1    1    0    1    0    1
[6,]    1    1    0    1    1    0    1    0    1
[7,]    0    1    0    1    1    0    1    0    1
[8,]    1    0    0    0    0    0    0    0    0

这是第一种方式

> x <- list(1:3,4:6,7:9)
> do.call(cbind, lapply(x, function(i) ifelse(rowSums(Q[,i]>=1), 1,0)))
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    0    0
[3,]    0    0    0
[4,]    1    0    0
[5,]    1    1    1
[6,]    1    1    1
[7,]    1    1    1
[8,]    1    0    0
> 

这是第二种方式,它更好

> Q.t <- data.frame(t(Q))
> n <- 3
> Q.t$groups <- rep(seq(1:(ncol(Q)/n)), each = n, len = (ncol(Q)))
> QT <- data.table(Q.t)
> setkey(QT, groups)
> Q.level <- QT[,lapply(.SD,sum), by = groups]
> Q.level <- t(Q.level)
> Q.level <- Q.level[-1,]
> apply(Q.level,2, function(x) ifelse(x>=1,1,0))
   [,1] [,2] [,3]
X1    1    1    1
X2    1    0    0
X3    0    0    0
X4    1    0    0
X5    1    1    1
X6    1    1    1
X7    1    1    1
X8    1    0    0
>