使用分组变量按列拆分 data.frame
根据分组因素按行分割 data.frame
是相当容易的。但是我如何按列拆分并可能应用函数?
my.df <- data.frame(a = runif(10),
b = runif(10),
c = runif(10),
d = runif(10))
grp <- as.factor(c(1,1, 2,2))
我想要的是按组划分的列的平均值。
到目前为止我所拥有的是一个穷人的申请。
lapply(as.list(as.numeric(levels(grp))), FUN = function(x, cn, data) {
rowMeans(data[grp %in% x])
}, cn = grp, data = my.df)
编辑 感谢大家的参与。我运行了 10 次重复*,我的工作 data.frame 大约有 22000 行。这些是几秒钟内的结果。
Roman: 2.19
Joris: 4.60
Joris #2: 3.79 #changed sapply to lapply as suggested by Joris in the [R chatroom][1].
Gavin: 4.70
James & EDi: > 200 # * ran only one replicate due to the large order of magnitude difference
让我感到奇怪的是,手头的任务没有包装函数。也许有一天我们能够做到
apply(X = my.df, MARGIN = 3, INDEX = my.groups, FUN = mean) # :)
It's fairly easy to split a data.frame
by rows depending on a grouping factor. But how do I split by columns and possibly apply a function?
my.df <- data.frame(a = runif(10),
b = runif(10),
c = runif(10),
d = runif(10))
grp <- as.factor(c(1,1, 2,2))
What I would like to have is a mean of colums by groups.
What I have so far is a poor man's apply.
lapply(as.list(as.numeric(levels(grp))), FUN = function(x, cn, data) {
rowMeans(data[grp %in% x])
}, cn = grp, data = my.df)
EDIT
Thank you all for participating. I ran 10 replicates* and my working data.frame has roughly 22000 rows. These are the results in seconds.
Roman: 2.19
Joris: 4.60
Joris #2: 3.79 #changed sapply to lapply as suggested by Joris in the [R chatroom][1].
Gavin: 4.70
James & EDi: > 200 # * ran only one replicate due to the large order of magnitude difference
It struck me as odd that there is no wrapper function for the task at hand. Maybe someday we'll be able to do
apply(X = my.df, MARGIN = 3, INDEX = my.groups, FUN = mean) # :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用相同的逻辑,但采用更方便的形式:
You can use the same logic, but in a more convenient form :
将
my.df
转换为列表并拆分它,然后在强制转换为数据框后将函数应用于列表组件的每个子集:这给出:
这相当于 @Roman 的“穷人的apply”:
组件上的名称除外。
Convert
my.df
to a list and split that, then apply your function to each subset of components of the list, after coercing to a data frame:This gives:
Which is equivalent to @Roman's "poor man's apply":
except for the names on the components.
这有效吗?
Is this working?
怎么样:
How about: