gpt4 book ai didi

r - 如何加入使用 plyr 函数拆分的数据框列表

转载 作者:行者123 更新时间:2023-12-04 12:34:36 29 4
gpt4 key购买 nike

我使用了plyr 包提供的strip_splits(df) 函数来获取数据框列表。我现在想将数据框列表连接在一起,并添加回用于拆分它们的变量。下面突出显示的文档使我相信这应该是可能的,但是我找不到合适的函数。

This is useful when you want to perform some operation to every column in the data frame, except the variables that you have used for splitting. These variables will be automatically added back on to the result when combining all results together.

例子:

dfSplit <- dlply(mtcars, c("vs", "am"), strip_splits)
df <- dfSplit[[1]]
score <- function(df) {
df$score <- apply(apply(df, 2, scale), 1, mean, na.rm = TRUE)
return(df)
}
dfSplit <- lapply(dfSplit, score)

如何将列表 dfSplit 中的数据框再次组合在一起?

编辑:组合数据框应包含列 vsam

最佳答案

使用 dplyr 中的 bind_rows():

library(dplyr)
bind_rows(dfSplit)

或者使用基础 R:

do.call(rbind, dfSplit)

给出:

#Source: local data frame [32 x 10]
#
# mpg cyl disp hp drat wt qsec gear carb score
#1 18.7 8 360.0 175 3.15 3.440 17.02 3 2 -0.18850120
#2 14.3 8 360.0 245 3.21 3.570 15.84 3 4 0.05315376
#3 16.4 8 275.8 180 3.07 4.070 17.40 3 3 -0.15909455
#4 17.3 8 275.8 180 3.07 3.730 17.60 3 3 -0.14033030
#5 15.2 8 275.8 180 3.07 3.780 18.00 3 3 -0.16788329
#6 10.4 8 472.0 205 2.93 5.250 17.98 3 4 0.42384103
#7 10.4 8 460.0 215 3.00 5.424 17.82 3 4 0.49006288
#8 14.7 8 440.0 230 3.23 5.345 17.42 3 4 0.79264565
#9 15.5 8 318.0 150 2.76 3.520 16.87 3 2 -0.79767163
#10 15.2 8 304.0 150 3.15 3.435 17.30 3 2 -0.53819495
#.. ... ... ... ... ... ... ... ... ... ...

关于r - 如何加入使用 plyr 函数拆分的数据框列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31258303/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com