繁体   English   中英

如何根据其他两列的值向数据框中添加一列? 电阻

[英]How to add a column to a dataframe based on the value of two other columns? R

我必须根据两个类别找到值 x 的平均值:


set.seed(42)  ## for sake of reproducibility
n <- 12
dat <- data.frame(group=rep(LETTERS[1:2], n/2),
type=rep(1:3,times=4), x=rnorm(n))


   group type           x
1      A    1  1.37095845
2      B    2 -0.56469817
3      A    3  0.36312841
4      B    1  0.63286260
5      A    2  0.40426832
6      B    3 -0.10612452
7      A    1  1.51152200
8      B    2 -0.09465904
9      A    3  2.01842371
10     B    1 -0.06271410
11     A    2  1.30486965
12     B    3  2.28664539

我想要这样的输出:(为了清楚起见,“等等”意味着前两行的平均计算相同,我懒得手工计算)

  group type        mean
1     A    1 1.441240225
2     A    2 0.854568985
3     A    3   and so on
4     B    1   and so on
5     B    2   and so on
6     B    3   and so on

我研究了 dplyr 工具,这些工具将帮助我按类型或按组获得 x 的平均值,但不能同时通过两者获得。

library(dplyr)

dat %>% 
  group_by(group, type) %>% 
  summarize(x = mean(x), .groups = "drop")

或者在带有aggregate基础 R 中

aggregate(x ~ group + type, dat, mean)

输出

# A tibble: 6 x 3
  group  type      x
  <chr> <int>  <dbl>
1 A         1  1.44 
2 A         2  0.855
3 A         3  1.19 
4 B         1  0.285
5 B         2 -0.330
6 B         3  1.09 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM