我有兩組列,每組 36 列,我想將組 1 的所有第 i 列與組 2 的第 i 列相加,得到 36 列。每個組中的列數在我的代碼中沒有固定,盡管每個組的列數相同。
例如。我擁有的:
teste <- tibble(a1=c(1,2,3),a2=c(7,8,9),b1=c(4,5,6),b2=c(10,20,30))
a1 a2 b1 b2
<dbl> <dbl> <dbl> <dbl>
1 1 7 4 10
2 2 8 5 20
3 3 9 6 30
我想要的是:
resultado <- teste %>%
summarise(
a_b1 = a1 b1,
a_b2 = a2 b2
)
a_b1 a_b2
<dbl> <dbl>
1 5 17
2 7 28
3 9 39
用 dplyr 執行這個操作會很好。
我會感謝任何幫助。
uj5u.com熱心網友回復:
teste %>%
summarise(across(starts_with("a")) across(starts_with("b")))
# A tibble: 3 x 2
a1 a2
<dbl> <dbl>
1 5 17
2 7 28
3 9 39
uj5u.com熱心網友回復:
您將很難找到像基本 R 解決方案一樣簡單優雅的 dplyr 解決方案:
teste[1:2] teste[3:4]
#> a1 a2
#> 1 5 17
#> 2 7 28
#> 3 9 39
雖然我猜在 dplyr 中你會得到相同的結果:
teste %>% select(starts_with("a")) teste %>% select(starts_with("b"))
uj5u.com熱心網友回復:
這也可能有助于基礎 R:
as.data.frame(do.call(cbind, lapply(split.default(teste, sub("\\D(\\d )", "\\1", names(teste))), rowSums, na.rm = TRUE)))
1 2
1 5 17
2 7 28
3 9 39
uj5u.com熱心網友回復:
另一種dplyr解決方案。我們可以使用rowwise和c_across來對每行的值求和。請注意,在這種情況下我們可以添加na.rm = TRUE到sum函式中。
library(dplyr)
teste2 <- teste %>%
rowwise() %>%
transmute(a_b1 = sum(c_across(ends_with("1")), na.rm = TRUE),
a_b2 = sum(c_across(ends_with("2")), na.rm = TRUE)) %>%
ungroup()
teste2
# # A tibble: 3 x 2
# a_b1 a_b2
# <dbl> <dbl>
# 1 5 17
# 2 7 28
# 3 9 39
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/350437.html
上一篇:Shiny中列之間的垂直分隔線
下一篇:重構任意嵌套的串列
