1

我正在尝试用 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", 
   mutate(gender = ifelse(resident == "YES" & id %in% female_index, "Female", "Female"))))

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

mutate_impl(.data, dots) 中的错误:
缺少参数“.data”,没有默认值

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

4

1 回答 1

2

您不需要mutateifelse.

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
于 2017-04-05T12:22:36.930 回答