我有:
library(tidyverse)
df <- tibble(one=c(1,1,1,2,2,2,3,3),
log1 = c(TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE),
log2 = c(TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE),
log3 = c(TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE))

我想查找每個列和組中出現“FALSE”一詞的次數并回傳一個 df

我已經嘗試map_df(df, function(x) sum(x==FALSE))過
df %>%
group_by(one) %>%
map_df( function(x) sum(x==FALSE))
但它們不會分成不同的組。
這也出錯了
df %>%
group_by(one) %>%
summarise( function(x) sum(x==FALSE))
有什么建議?
uj5u.com熱心網友回復:
您可以用于across處理多個列
library(dplyr)
df %>%
group_by(one) %>%
summarise(across(starts_with("log"), function(x) sum(x==F)))
# A tibble: 3 × 4
one log1 log2 log3
<dbl> <int> <int> <int>
1 1 1 1 1
2 2 3 3 3
3 3 0 2 1
正如@RuiBarradas 所提到的,執行邏輯的一種不錯且更短的方法是直接使用布林值
...
summarise(across(starts_with("log"), function(x) sum(!x)))
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/426678.html
上一篇:將ID列添加到資料框串列
