Lapply将行附加到矩阵

时间:2016-07-12 09:22:08

标签: r matrix row lapply

我难以在lapply循环中填充矩阵。

在我的数据中,我有135个地理空间点的列表。在lapply循环中,我基于来自这些站点坐标的3个不同半径内的景观计算各种度量。我想做的是循环遍历135个站点和3个半径的每个组合,然后用(站点,半径,公制1,公制2,公制3)填充我的空白预备矩阵的每一行。

我创建了一个简单的脚本来复制我遇到的问题。如果我可以在here中应用do.call(rbind, absdf)命令,那么我还没有弄清楚如何......

# Generate empty matrix:
mymatrix <- matrix(,nrow=18, ncol=5)

# A vector with length of x (in my data this is the list of 135 sites):
a <- 1:6
#These sets will represent my metrics 
b <- rnorm(6, 5, 10)
c <- rnorm(6, 100, 20)
d <- rnorm(6, 20, 20)

# Radius vector:
rad <- c(100,200,300)

# The loop: lapply for site within lapply for radius
lapply(1:3,function(r){
  lapply(1:6,function(x){
  row.number <- (r-1)*6+x 
  tmpvector <- c(a[x], b[x], c[x], d[x], rad[r])
  mymatrix[row.number,] <- tmpvector
  })
})
View(mymatrix)

使用现在编写的代码,结果矩阵仍为空白。

如果我把这个简单的例子写成for循环

mymatrix <- matrix(,nrow=18, ncol=5)

a <- 1:6
b <- rnorm(6, 5, 10)
c <- rnorm(6, 100, 20)
d <- rnorm(6, 20, 20)

rad <- c(100,200,300)

for (r in 1:3) {
  for (x in 1:6) {
    row.number <- (r-1)*6+x 
    tmpvector <- c(a[x], b[x], c[x], d[x], rad[r])
    mymatrix[row.number,] <- tmpvector
  }
} 
View(mymatrix)

然后矩阵填充我期望的值。如果我犯了一个简单的错误,我道歉:我对这些循环很新!

NB我也愿意创建这个数据的连续列表,然后我可以将其转换为更有用的格式!

2 个答案:

答案 0 :(得分:1)

在这种情况下使用lapply并不是很自然。您根本不需要循环来创建这样的矩阵,您可以使用R的循环特性。

mymatrix <- cbind(a, b, c, d, rep(c(100,200,300), each = 6))

答案 1 :(得分:0)

如果你真的想用lapply来做,这里有一个非常难看的方式(你自己就在那里):

set.seed(123)
#we don't really need to initialise the matrix anymore
#mymatrix <- matrix(,nrow=18, ncol=5)

a <- 1:6
b <- rnorm(6, 5, 10)
c <- rnorm(6, 100, 20)
d <- rnorm(6, 20, 20)
rad <- c(100,200,300)

#Generate the list of rows:
rowList<-lapply(1:3,function(r){
                    lapply(1:6,function(x){
                               #data processing
                               #row.number <- (r-1)*6+x #actually this line is unnecessary
                               tmpvector <- c(a[x], b[x], c[x], d[x], rad[r])
                    })
})

#creation of mymatrix -- method 1
mymatrix<-as.matrix(data.frame(rowList))
colnames(mymatrix)<-NULL #since you probably don't want the ugly output
mymatrix<-t(mymatrix)   

###   OR 
#creation of my matrix -- method2 (with do.call and rbind)
do.call(rbind,sapply(rowList,matrix))

初始方法的问题(即尝试更改lapply中的矩阵)是在每次迭代结束时返回您创建的最后一个结果:创建当前行和as没有创建错误,消息或警告,您没有任何输出。

mymatrix保持在lapply循环之前,因为所有处理都在{}内完成,并且也没有保存。

顺便说一句,如果你想对lapply的输出做任何事情,你应该将它们保存在一个对象中(或者直接将它们插入另一个函数中,如果你对内部不太感兴趣我不会推荐它lapply的逻辑。)

希望我的解释不是太复杂而且有点偏离主题,但是开始使用* apply系列和等效的好地方:R Grouping functions: sapply vs. lapply vs. apply. vs. tapply vs. by vs. aggregate

相关问题