条件变异的 SE 问题

SE issue with conditional mutate

我正在尝试使用 mutate 做一个简单的条件。

代码应基于同一数据帧中的两个变量创建一个名为 "gender" 的新变量。

sample <- data.frame(
   client = c("john", "peter", "hanna", "lisa"), 
   id = c(100, 400,  650, 700),
   resident = c('YES', 'YES', 'YES', 'NO'))

 male_index <- as.vector(000:499)
 female_index <- as.vector(500:999)

 sample <- sample %>%
   mutate(gender = ifelse(resident == "YES" & id %in% male_index, "Male", 
   mutate(gender = ifelse(resident == "YES" & id %in% female_index, "Female", "Female"))))

我收到以下错误,我不明白。我想这与SE有关。但是我对R还是不太熟悉。

Error in mutate_impl(.data, dots) :
argument ".data" is missing, with no default

如果我 运行 使用单个 mutate 语句的代码,我不会遇到任何问题。

您不需要 ifelse 中的第二个 mutate 调用。

sample <- data.frame(
  client = c("john", "peter", "hanna", "lisa"),
  id = c(100, 400,  650, 700),
  resident = c('YES', 'YES', 'YES', 'NO')
)

male_index <- as.vector(000:499)
female_index <- as.vector(500:999)

sample <- sample %>%
  mutate(gender = ifelse(
    resident == "YES" & id %in% male_index,
    "Male",
    ifelse(resident == "YES" &
             id %in% female_index, "Female", "Non-resident")
  ))

现在数据集中的每个人都有一个指定的值 gender

sample
#  client  id resident gender
#1   john 100      YES   Male
#2  peter 400      YES   Male
#3  hanna 650      YES Female
#4   lisa 700       NO Non-resident