英文:
Generating a new variable if any of the conditions are met without list all variables in R
问题
我想生成一个名为outcome的变量,如果以下数据集中的任何列具有任何形式的同意响应,将其分配为1,否则分配为0。但是,我不想在我的代码中列出所有变量。
我尝试了以下代码:
vars <- c("a1", "a2", "a3", "a4")
dat <- dat %>%
mutate(outcome = case_when(if_any(vars, ~ .x == "consented now" | "consented later") ~ 1))
数据集
dat1 <- tibble(
a1 = c("consented now", NA, NA, NA),
a2 = c("", "Refused", NA, NA),
a3 = c(NA, "consented now", NA, NA),
a4 = c(NA, NA, NA, "consented later"))
希望这有所帮助。
英文:
I would like to generate a variable called outcome which assigns 1 if any of the columns in the dataset below have any form of consent response else assign 0. However, I do not want to list all variables in my code.
I have tried the following code;
vars<-c("a1","a2","a3","a4")
dat<-dat%>%
mutate(outcome = case_when(if_any(vars, ~ .x == "consented now"|
"consented later") ~ 1))
dataset
dat1 <- tibble(
a1 = c("consented now", NA, NA, NA),
a2= c("", "Refused", NA, NA),
a3= c(NA, "consented now", NA, NA),
a4= c(NA, NA, NA, "consented later"))
答案1
得分: 1
不需要使用 `case_when`,可以使用 `if_any` 和 `grepl` 来实现:
```r
dat1 %>%
mutate(outcome = +if_any(a1:a4, ~ grepl("consented", .x)))
输出:
# A tibble: 4 × 5
# a1 a2 a3 a4 outcome
# <chr> <chr> <chr> <chr> <int>
#1 consented now "" NA NA 1
#2 NA "Refused" consented now NA 1
#3 NA NA NA NA 0
#4 NA NA NA consented later 1
英文:
You don't need case_when
, with if_any
and grepl
:
dat1 %>%
mutate(outcome = +if_any(a1:a4, ~ grepl("consented", .x)))
output
# A tibble: 4 × 5
# a1 a2 a3 a4 outcome
# <chr> <chr> <chr> <chr> <int>
#1 consented now "" NA NA 1
#2 NA "Refused" consented now NA 1
#3 NA NA NA NA 0
#4 NA NA NA consented later 1
答案2
得分: 1
使用paste
、do.call
和grepl
的基本变体可能如下所示:
dat1$outcome <- +grepl("consented", do.call(paste, dat1))
dat1
# a1 a2 a3 a4 outcome
#1 consented now <NA> <NA> 1
#2 <NA> Refused consented now <NA> 1
#3 <NA> <NA> <NA> <NA> 0
#4 <NA> <NA> <NA> consented later 1
或者使用rowSums
和sapply
。
dat1$outcome <- +(rowSums(sapply(dat1, grepl, pattern="consented")) > 0)
英文:
A base variant using paste
with do.call
and grepl
might be:
dat1$outcome <- +grepl("consented", do.call(paste, dat1))
dat1
# a1 a2 a3 a4 outcome
#1 consented now <NA> <NA> 1
#2 <NA> Refused consented now <NA> 1
#3 <NA> <NA> <NA> <NA> 0
#4 <NA> <NA> <NA> consented later 1
Or using rowSums
and sapply
.
dat1$outcome <- +(rowSums(sapply(dat1, grepl, pattern="consented")) > 0)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论