簡體   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