r - 根据因子的级别将 data.frame 拆分为新的 data.frames

标签 r dataframe r-faq

我正在尝试创建单独的 data.frame基于因子水平的对象。所以如果我有:

df <- data.frame(
  x=rnorm(25),
  y=rnorm(25),
  g=rep(factor(LETTERS[1:5]), 5)
)

如何拆分 df分成单独的 data.frame s 代表 g 的每个级别包含相应的 xy值(value)观?我可以使用 split(df, df$g) 到达那里的大部分路线,但我希望因子的每个级别都有自己的 data.frame .

做到这一点的最佳方法是什么?

最佳答案

我认为split做你想要的。

请注意,X 是一个数据框列表,如 str 所示。 :

X <- split(df, df$g)
str(X)

如果您想要具有组 g 名称的单个对象,您可以从 split 分配 X 的元素到这些名称的对象,虽然这似乎是额外的工作,当您可以从列表中索引数据框 split创造。
#I used lapply just to drop the third column g which is no longer needed.
Y <- lapply(seq_along(X), function(x) as.data.frame(X[[x]])[, 1:2]) 

#Assign the dataframes in the list Y to individual objects
A <- Y[[1]]
B <- Y[[2]]
C <- Y[[3]]
D <- Y[[4]]
E <- Y[[5]]

#Or use lapply with assign to assign each piece to an object all at once
lapply(seq_along(Y), function(x) {
    assign(c("A", "B", "C", "D", "E")[x], Y[[x]], envir=.GlobalEnv)
    }
)

编辑 甚至比使用 lapply 更好分配给全局环境使用 list2env :
names(Y) <- c("A", "B", "C", "D", "E")
list2env(Y, envir = .GlobalEnv)
A

关于r - 根据因子的级别将 data.frame 拆分为新的 data.frames,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9713294/

相关文章:

python - 用python读取一个复杂的CSV文件

r - R 中结束 "+"提示

r - 'pipe' 、 'dot' 和 'dollar' 运算符的串联似乎在 R 中起作用?

r - 如何确定以system(...,wait = FALSE)开始的进程何时结束

r - 如何更改ggplot条形图中的原点线位置?

r - 如何过滤数据框

r - ggplot2 折线图给出 "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

r - R中的双重居中

python - 如何在最小值和最大值之间对 pandas 数据框进行分类/标记

python-2.7 - 以文件名作为列标题将多个 *.txt 文件读入 Pandas Dataframe