我有一个函数可以接收长格式数据并检查每个组是否具有唯一值。当该组没有唯一值时它报告 1,否则报告 0。当我通过数据框的一列时,它正确地给出值 1 以指示其中一个组具有所有相同的值。但是,当我通过 apply 传递该函数时,我得到了一个与以前不同的值。 任何帮助将不胜感激。
谢谢
check_repeated <- function(df, group_var, value_var) {
# Group the data by the specified variable
grouped_df <- df %>%
group_by({{group_var}})
# Check if all values in the variable are repeated within each group
all_repeated <- grouped_df %>%
summarise(n_distinct = n_distinct({{value_var}})) %>%
pull(n_distinct) == 1
return(sum(all_repeated))
}
df <- data.frame(
group = rep(c("A", "B"), each = 3),
value1 = c(2, 5, 3, 1, 4, 6),
value2 = c("w", "w", "w", "r","r","w"),
value3 = c(2,2,2,2,3,2)
)
apply(df[,-1], 2, check_repeated, df=df, group_var=df$group)
check_repeated(df, group, value2)
我们可以做
library(dplyr)
df %>%
summarise(across(starts_with('value'), n_distinct), .by = 'group')