Create New Variable by Multiple Conditions via Mutate Case_When

Create new variable by multiple conditions via mutate case_when

The issue is in the use of assignment operator = instead of comparison ==

library(dplyr)
test<- test%>%
mutate(WHRcat = case_when((WHR >= 1.02 & sexe == 1) ~ 1,
(WHR < 1.02 & sexe == 1) ~ 2,
(WHR >= 0.85 & sexe == 2) ~ 3,
(WHR < 0.85 & sexe == 2) ~ 4,
TRUE ~ 0))

R mutate() with varying multiple conditions given by case_when()

I made a toy example of a for loop mutate case_when with the iris dataset

The first complication is in a simple for (j in 1:10){out<-j} loop, the output data is overwritten with each subsequent iteration of j, and in the end, only the results of the 10th run are retained.

Then I learned about the coalesce() function; which combines (merges? unions? joins?) sparse data of equal length (similar to Microsoft Excel's, paste-special "skip blanks" transformation).

In the sample code below, we take the iris dataset, and loop from 1 to 10, and if iris$Sepal.Length (aka iris[,1]) is equal to the loop iteration j, we change the resulting variable (slope) to 100+j.

iris4 <- tibble(iris)

for (j in 1:10) {
iris4 <- coalesce(iris4 %>% mutate(Slope = case_when(Sepal.Length == j ~ 100+j)),iris4)}

table(iris4$Slope)

mutate and if_any with condition over multiple columns

The syntax was slightly wrong, but you were close. Note that if_any works like across, so like this if_any(columns, condition), and you should use function, \ or ~ to specify the condition.

df %>% 
mutate(cod = case_when(if_any(starts_with("string"), ~ .x == "a") ~ 1))

string1 string2 string3 id cod
1 a d a 1 1
2 b a d 2 1
3 c f c 3 NA

creating new column with case_when when multiple conditions need to be satisfied

Will this work:

df %>%
mutate(
flag=case_when(str_detect(record, str_c(code_flag, collapse = '|')) & str_sub(record, start=2, end=2) == "4" & age >=18 ~ "yes", TRUE ~ "no")
)
id record age flag
1 1 A4B 12 no
2 1 AAA 12 no
3 2 B45 18 no
4 2 BBB 18 no
5 3 B4A4 22 yes
6 3 CA4 22 no


Related Topics



Leave a reply



Submit