简体   繁体   English

R 中具有多个输出的管道和 If 语句

[英]Piping and If statement with multiple outputs in R

What am I missing here...我在这里想念什么...

df <- data.frame("sn" = 1:3, "age" = c(21,15, 18), "name" = c("John","Dora", "Lynn"))

df %>% if (df$age >= 18){
  df$drive <- "yes"
  df$vote <- "yes"
}

Error in if (.) df$age >= 18 else { : 
  argument is not interpretable as logical

...in trying to make this dataframe? ...试图制作这个 dataframe?

  sn age name drive vote
1  1  21 John   yes  yes
2  2  15 Dora    no   no
3  3  21 Lynn   yes  yes

We could use ifelse or case_when as these are vectorized while if/else is not ie it expects a vector of length 1 as logical vector我们可以使用ifelsecase_when因为它们是向量化的,而if/else不是,即它期望长度为 1 的向量作为逻辑向量

library(dplyr)
df %>%
     mutate(drive = case_when(age >=18 ~ "yes", TRUE ~"no"),
             vote = drive)

In base R , we can dobase R中,我们可以做

df[c('drive', 'vote')] <- 'no'
df[df$agge >=18, c('drive', 'vote')] <- 'yes'

We can compare age with 18 and assign "yes" , "no" values based on that.我们可以将age与 18 岁进行比较,并在此基础上分配"yes""no"值。 Since the age for driving and voting is the same we can use the same values for vote as well.由于驾驶和投票的年龄相同,我们也可以使用相同的值进行vote

df$drive <- c('no', 'yes')[(df$age >= 18) + 1]
df$vote <- df$drive
df

#  sn age name drive vote
#1  1  21 John   yes  yes
#2  2  15 Dora    no   no
#3  3  18 Lynn   yes  yes

We can also use ifelse / if_else to get output here but it would be slower than the above approach.我们也可以在这里使用ifelse / if_else来获取 output 但它会比上述方法慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM