gpt4 book ai didi

r - 测试 dplyr 中列子集的相等性

转载 作者:行者123 更新时间:2023-12-04 02:35:11 25 4
gpt4 key购买 nike

假设我有以下 df:

mydf <- data.frame(col1 = c("Red", "Red", "Blue", "Orange"),
col2 = c("Red", "Blue", NA, "Red"),
col3 = c("Red", "Red", "Blue", "Red"),
col4 = c("Red", "Red", "Blue", "Blue"))

我想创建一个名为 "all_equal" 的列,如果 1-4 列中的所有 non_NA 值都等于相同的值,则该列设置为 1。这应该导致以下结果:

    col1 col2 col3 col4 all_true
1 Red Red Red Red TRUE
2 Red Blue Red Red FALSE
3 Blue <NA> Blue Blue TRUE
4 Orange Red Red Blue FALSE

请注意,第二列中的 NA 不应计入相等性。我试过使用 all 来测试是否相等,但它似乎在 dplyr 链中效果不佳。

最佳答案

您可以将 c_across()rowwise() 一起使用。

library(dplyr)

mydf %>%
rowwise() %>%
mutate(all_true = n_distinct(c_across(col1:col4), na.rm = T) == 1) %>%
ungroup()

# # A tibble: 4 x 5
# col1 col2 col3 col4 all_true
# <chr> <chr> <chr> <chr> <lgl>
# 1 Red Red Red Red TRUE
# 2 Red Blue Red Red FALSE
# 3 Blue NA Blue Blue TRUE
# 4 Orange Red Red Blue FALSE

关于r - 测试 dplyr 中列子集的相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62285603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com