我發現自己經常這樣做。
set.seed(123)
test_data=data.frame(sample=sample(LETTERS[1:10], 100,replace = TRUE), type=sample(letters[1:2], 100, replace=TRUE ), area=sample(1:100, replace=TRUE) )
test_data 的內容為:
head(test_data)
sample type area
1 C b 24
2 C b 63
3 J a 54
4 B b 23
5 F a 26
6 E a 33
我通常想通過一些分組屬性對特定列求和,為此我使用:
res_sum=test_data %>% group_by(sample, type) %>% summarise_at( .vars = "area", .funs = sum )
到目前為止一切順利,當我想將結果置于“良好”格式時,問題就來了。下面幾行將結果按照我想要的方式放置,但我發現這種方式很麻煩。
res_sum_a=res_sum[res_sum$type=="a", ]
colnames(res_sum_a)[3]=paste0( colnames(res_sum)[3], ".a")
res_sum_b=res_sum[res_sum$type=="b", ]
colnames(res_sum_b)[3]=paste0( colnames(res_sum)[3], ".b")
res_df=merge(res_sum_a[,c(1,3)], res_sum_b[, c(1,3)], by="sample", all=TRUE)
head(res_df)
sample area.a area.b
1 A 244 147
2 B 17 152
3 C 153 541
4 D 107 94
5 E 246 266
6 F 189 286
請注意,原始資料框中可能有超過 2 個“型別”(因此,如 a、b、c ....)。有沒有辦法,這樣做更 dplyr 慣用?謝謝。
uj5u.com熱心網友回復:
您指的是pivoting,它由單獨的包 ( {tidyr}) 提供。
我還將您的 dplyr 代碼更新為最新的語法(例如,summarise_at()已被 替換across())。
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(tidyr)
set.seed(123)
test_data=data.frame(sample=sample(LETTERS[1:10], 100,replace = TRUE), type=sample(letters[1:2], 100, replace=TRUE ), area=sample(1:100, replace=TRUE) )
test_data |>
group_by(sample, type) |>
summarise(across(area, sum)) |>
tidyr::pivot_wider(names_from = type, values_from = area)
#> `summarise()` has grouped output by 'sample'. You can override using the
#> `.groups` argument.
#> # A tibble: 10 x 3
#> # Groups: sample [10]
#> sample a b
#> <chr> <int> <int>
#> 1 A 244 147
#> 2 B 17 152
#> 3 C 153 541
#> 4 D 107 94
#> 5 E 246 266
#> 6 F 189 286
#> 7 G 48 483
#> 8 H 223 94
#> 9 I 285 345
#> 10 J 491 252
創建于 2022-11-16,使用reprex v2.0.2
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/534800.html
標籤:rdplyr
下一篇:從另一個資料框填充一個資料框的值
