2017-07-17 33 views
-1

重新定義矩陣的元素(DF)我想上R.如何使用分配ř

使用assign重新定義的多維矩陣的元素propperly我嘗試這個

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

第一個分配語句沒問題。一旦你通過調用'assign(paste(「STAT」,i,「[」,la,「,」,lo,「]」,sep =「」),...),你正在創建一個新的變量而且你沒有訪問你已經創建的那個。 –

+0

但是我如何訪問我已經創建的那個?謝謝@AGore – Forever

+0

https://stats.stackexchange.com/questions/10838/produce-a-list-of-variable-name-in-a-for-loop-then-assign-values-to-them –

回答

1

既然你不提供你的數據,我做了一些:

lat = 3 
lon = 3 
otherDF <- data.frame(A=1:3, B=4:6, C=7:9) 
loidx <- 1:3 
laidx <- 1:3 

我避免嵌套的for循環和第二assign語句expand.gridsapply(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)) 
} 

我讓你根據你的代碼想要的一些猜測,所以編輯您原來的職位,如果你想要的東西不同。

+0

我編輯了原帖,otherDF也是一個多維矩陣 – Forever