有条件变异的SE问题

时间:2017-04-05 12:20:03

标签: r dplyr non-standard-evaluation standard-evaluation

我正在尝试用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. <​​/ p>

  

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

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

1 个答案:

答案 0 :(得分:2)

您的mutate中不需要第二次ifelse来电。

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