这是前一个问题的变体。
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")我希望将数据分割为在下划线"_“之后在column.names中给出的索引。(索引可以是任意长度的字符/数字;这些只是随机的例子)。
indx <- gsub(".*_", "", names(df))并将结果命名为相应的数据格式,最后我想得到三个数据文件,名为:
谢谢!
发布于 2014-12-16 09:45:07
在这里,您可以通过indx拆分列名,使用lapply和[获取列表中的数据子集,使用setNames设置列表元素的名称,如果需要将它们作为单独的数据集使用list2env (不推荐这样做,因为大多数操作可以在列表中完成,如果需要,则可以使用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,并使用[提取列,其余的如上面所示。
list2env(setNames(Map(`[` ,
list(df), split(colnames(df), indx)),
paste('df',unique(sort(indx)), sep="_")), envir=.GlobalEnv)更新
你可以:
indx1 <- factor(indx, levels=unique(indx))
split(colnames(df), indx1)发布于 2014-12-16 09:47:33
你可以试试这个:
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.5054421https://stackoverflow.com/questions/27501615
复制相似问题