[英]Summarise logical statement in if condition
我有一個數據框,其中有一列名為“col0”和幾個(超過 100 個)其他列(col1、col2、col3...)。 我試圖用 dplyr 有條件地總結它們(col0 的總和和其他的 weighted.mean 的總和),但它不起作用,因為它總結了列中的所有值。
我認為 if 語句之后存在偏差。
代碼:
dt <- data.frame(col0 = c(1,2,3),
col1 = c(0.1,0.2,0.3),
col2 = c(0.2,0.3,0.4),
col3 = c(0.1,0.2,0.3),
col4 = c(0.2,0.3,0.4))
dt %>%
summarise(across(everything(), ~ if(any(names(.) != "col0"))
weighted.mean(., col0, na.rm = TRUE)
else sum(., na.rm = TRUE)))
結果:
col0 col1 col2 col3 col4
1 6 0.6 0.9 0.6 0.9
注意: Ronak Shah建議的解決方案是正確的,但(無論出於何種原因)我必須在 weighted.mean 函數中明確定義 wt
您可以使用cur_column()
來獲取列名。
library(dplyr)
dt %>%
summarise(across(everything(), ~ if(cur_column() != 'col0')
weighted.mean(., col0, na.rm = TRUE)
else sum(., na.rm = TRUE)))
# col0 col1 col2 col3 col4
#1 6 0.2333333 0.3333333 0.2333333 0.3333333
另一種方法是分別應用col0
的函數。
dt %>%
summarise(across(-col0, weighted.mean, col0, na.rm = TRUE),
col0 = sum(col0))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.