如何使用赋值R重新定义矩阵的元素(df)

时间:2017-07-17 13:05:11

标签: r dataframe

我想在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]]``

请帮忙

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

我使用assignexpand.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))
}

我根据您的代码对您想要的内容做了一些猜测,所以如果您想要不同的内容,请编辑原始帖子。