按列名索引拆分数据框

时间:2014-12-16 09:42:37

标签: r

这是先前问题的变体。

df <- data.frame(matrix(rnorm(9*9), ncol=9))
names(df) <- c("c_1", "d_1", "e_1", "a_p", "b_p", "c_p", "1_o1", "2_o1", "3_o1")

我想通过下划线&#34; _&#34;之后的column.names中给出的索引来拆分数据帧。 (索引可以是不同长度的任何字符/数字;这些只是随机的例子。)

indx <- gsub(".*_", "", names(df))

并相应地命名结果数据帧,最后我希望获得三个数据帧,名为:

  • df_1
  • df_p
  • df_o1

谢谢!

2 个答案:

答案 0 :(得分:4)

在这里,您可以按indx拆分列名,使用lapply[获取列表中的数据子集,使用{{1}设置列表元素的名称如果您需要将它们作为单独的数据集,则使用setNames(不推荐使用,因为大多数操作都可以在列表中完成,以后如果需要,可以使用list2env与{ {1}}。

write.table

或使用lapply。这类似于上述方法即。按 list2env( setNames( lapply(split(colnames(df), indx), function(x) df[x]), paste('df', sort(unique(indx)), sep="_")), envir=.GlobalEnv) head(df_1,2) # c_1 d_1 e_1 #1 1.0085829 -0.7219199 0.3502958 #2 -0.9069805 -0.7043354 -1.1974415 head(df_o1,2) # 1_o1 2_o1 3_o1 #1 0.7924930 0.434396 1.7388130 #2 0.9202404 -2.079311 -0.6567794 head(df_p,2) # a_p b_p c_p #1 -0.12392272 -1.183582 0.8176486 #2 0.06330595 -0.659597 -0.6350215 拆分列名称并使用Map提取列,其余部分如上所示。

indx

更新

你可以这样做:

[

答案 1 :(得分:3)

你可以试试这个:

 invisible(sapply(unique(indx),
                  function(x)                      
                     assign(paste("df",x,sep="_"),
                            df[,grepl(paste0("_",x,"$"),colnames(df))],
                            envir=.GlobalEnv)))

# the code applies to each unique element of indx the assignement (in the global environment) 
# of the columns corresponding to indx in a new data.frame, named according to the indx.
# invisible function avoids that the data.frames are printed on screen.

> ls()
[1] "df"    "df_1"  "df_o1" "df_p"  "indx"  

> df_1[1:3,]
         c_1        d_1        e_1
1  1.8033188  0.5578494  2.2458750
2  1.0095556 -0.4042410 -0.9274981
3  0.7122638  1.4677821  0.7770603

> df_o1[1:3,]
         1_o1        2_o1       3_o1
1 -2.05854176 -0.92394923 -0.4932116
2 -0.05743123 -0.24143979  1.9060076
3  0.68055653 -0.70908036  1.4514368

> df_p[1:3,]
         a_p        b_p        c_p
1 -0.2106823 -0.1170719  2.3205184
2 -0.1826542 -0.5138504  1.9341230
3 -1.0551739 -0.2990706  0.5054421