将数据列表分配给for循环中的变量

时间:2014-09-22 12:33:58

标签: r

我有一个存储在变量数据中的集合列表。我想将这些集合分别分配给变量,如下所示。

q1_set1_m <- data[["q1_set1_proj1"]]
q1_set2_m <- data[["q1_set2_proj1"]]
q1_set3_m <- data[["q2_set3_proj1"]]
q2_set1_m <- data[["q2_set1_proj1"]]
q2_set2_m <- data[["q2_set2_proj1"]]
q2_set3_m <- data[["q2_set3_proj1""]]
q3_set1_m <- data[["q3_set1_proj1""]]
q3_set2_m <- data[["q3_set2_proj1""]]
q3_set3_m <- data[["q3_set3_proj1""]]

由于变量数据有很多集,所以我尝试在for循环中执行此操作 方法1

  for(qNum in 1:3){
    for(setNum in 1:3){
                s1=as.character("[")
                s2=as.character("]")
                print(paste0("q_",qNum,"_set",setNum,"_m=","data",as.character(s1),as.character(s1),"q",qNum,"_",setNum,"_proj1",as.character(s2),as.character(s2)))
                }
}

方法2

for(qNum in 1:3){
    for(setNum in 1:3){
        s1=as.character("[")
        s2=as.character("]")
        var <-   paste0("=","data",as.character(s1),as.character(s1),"q",qNum,"_",setNum,"_proj1",as.character(s2),as.character(s2))

        assign(paste0("q_",qNum,"_set",setNum,"_m"), var)    
     }

}

数据

 str(data)
 List of 40
  $ merged_q1_set1_proj1:'data.frame':  1959931 obs. of  2 variables:
  ..$ V1: Factor w/ 54577 levels "XLOC_000001",..: 1 1 1 1 1 1 1 1 1 1 ...
  ..$ V2: Factor w/ 50648 levels "5S_rRNA","7SK",..: 14964 14964 14964 14964 14964 14964 14964   14964 14964 14964 ...
  $ merged_q1_set2_proj1:'data.frame':  1959267 obs. of  2 variables:
  ..$ V1: Factor w/ 53423 levels "XLOC_000001",..: 1 1 1 1 1 1 1 1 1 1 ...
  ..$ V2: Factor w/ 50633 levels "5S_rRNA","7SK",..: 14949 14949 14949 14949 14949 14949 14949 14949 14949 14949 ...
   $ merged_q2_set1_proj1:'data.frame': 1956746 obs. of  2 variables:
   .......

这只能打印变量名称和数据集。我不知道如何将数据集分配给不同的变量。

由于

1 个答案:

答案 0 :(得分:1)

如果数据是data.frame,您可以尝试(虽然不推荐assign):

set.seed(42)
dat1 <- as.data.frame(matrix(sample(1:25, 9*10, replace=TRUE), ncol=9)) 

colnames(dat1) <- paste(rep(paste0("q", 1:3), c(2,4,3)), rep(paste0("set",1:3), 3), "proj1", sep="_")
names1 <- paste(rep(paste0("q", 1:3), c(2,4,3)), rep(paste0("set", 1:3), 3), "m", sep="_") #if `names1` changes only at the last part,
#it could be changed easily in other ways.  But, I am using `paste` in case you want to delete/add extra things.

for(i in seq_along(names1)){ # looping over the names
    assign(names1[i], dat1[,i])
}

q1_set1_m
#[1] 23 24  8 21 17 13 19  4 17 18

q1_set2_m
#[1] 12 18 24  7 12 24 25  3 12 15

 dat1[,1]
 #[1] 23 24  8 21 17 13 19  4 17 18

更新

如果您有list

 lst1 <- as.list(dat1)
 for(i in seq_along(names1)){
 assign(names1[i], lst1[[i]])
 }

q1_set1_m
#[1] 23 24  8 21 17 13 19  4 17 18