You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中如何根据三列性别值的相等情况创建新分类变量

实现方法

tidyverse 方案(推荐,兼容性强)

你可以通过dplyr的行操作结合n_distinct快速实现需求,不管后续新增多少个作者性别列,只要列名以author开头都无需修改代码:

library(dplyr)

genders <- genders %>%
  # 按行处理
  rowwise() %>%
  mutate(gender_mix = case_when(
    # 统计当前行所有作者性别列的唯一值数量,为1说明全相同
    n_distinct(c_across(starts_with("author"))) == 1 ~ tolower(author1_gender),
    # 否则为混合
    TRUE ~ "mix"
  )) %>%
  # 取消行分组,避免影响后续操作
  ungroup()

base R 方案

如果你不想加载额外包,也可以用基础函数实现:

# 按行判断所有值是否唯一
all_same <- apply(genders, 1, function(x) length(unique(x)) == 1)
# 生成标识列
genders$gender_mix <- ifelse(all_same, tolower(genders$author1_gender), "mix")

运行上述任意一种代码,都能得到你预期的输出结果。


内容的提问来源于stack exchange,提问作者T. C. Nobel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 22:06:06