我想在R上使用assign
重新定义多维矩阵的适当元素。
我试过这个
lat = 3
lon = 3
laidx = 1:3
loidx = 1:3
OtherDF is a 3x3 multidimensional matrix, and each element is a large data frame
for (i in 1:12){
assign(paste("STAT",i,sep=""),array(list(NA), dim=c(length(lat),length(lon))))
for (lo in loidx){
for (la in laidx){
assign(paste("STAT",i,"[",la,",",lo,"]",sep=""), as.data.frame(do.call(rbind,otherDF[la,lo])))
# otherDF[la,lo] are data frames
}
}
}
首先我创建了12个空矩阵STATS1,STATS2,...,STATS12(我需要12个,每个月一个)
然后我尝试用其他数据框的元素填充它们,但不是填充它而是创建了许多新变量,如`STAT10 [[1,1]]``
请帮忙
答案 0 :(得分:1)
由于您没有提供数据,我编写了一些内容:
lat = 3
lon = 3
otherDF <- data.frame(A=1:3, B=4:6, C=7:9)
loidx <- 1:3
laidx <- 1:3
我使用assign
和expand.grid
避免使用嵌套for循环和第二个sapply(iter(idx,by="row", function(x) otherDF[x$Var1,x$Var2])
语句。
install.packages("iterators")
for (i in 1:12){
library(iterators)
idx <- expand.grid(loidx,laidx) # expands all combinations of elements in loidx and laidx
assign(paste0("STAT",i), matrix(sapply(iter(idx, by="row"), function(x) otherDF[x$Var1, x$Var2]), ncol=3))
}
我根据您的代码对您想要的内容做了一些猜测,所以如果您想要不同的内容,请编辑原始帖子。