Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

r - mutate und case_when with multiple cases

I would like to basically write a Syntax to get general scales to T-Scores. To norm these, there are two conditions, the gender and the age, which requires a separate T-Score.

So my data looks something like this:

w <- factor(c("m", "w", "w", "m", "m", "w", "w", "w", "m", "m"))
x <- c(28, 18, 25, 29, 21, 19, 27, 26, 31, 22)
y <- c(80, 55, 74, 101, 84, 74, 65, 56, 88, 78)
z <- c(170, 174, 183, 190, 185, 178, 169, 163, 189, 184)
bsp1 <- data.frame(w, x, y, z)
colnames(bsp1) <- c("Geschlecht", "Alter", "xx", "yy")
rm(w, x, y, z)
bsp1

So far, I've created something like this, even though in this example it's not complete.

bsp1 <- bsp1 %>%
  mutate(xxx =
           case_when(
             Geschlecht = "m" & Alter > 18 & xx == 55 ~ "1", 
             Geschlecht = "m" & Alter > 18 & xx == 56 ~ "2", 
             Geschlecht = "m" & Alter > 18 & xx == TRUE  ~ "3", 
           ))

I can't seem to figure out, how to combine these multiple conditions into the case_when function. Also, if there needs to be a TRUE statement for it at the end, where does it go?

I hope it's kind of understandable, what I want to do here. Thank you in advance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You probably meant to write :

library(dplyr)

bsp1 <- bsp1 %>%
          mutate(xxx =
                  case_when(
                    Geschlecht == "m" & Alter > 18 & xx == 55 ~ 1, 
                    Geschlecht == "m" & Alter > 18 & xx == 56 ~ 2, 
                    TRUE  ~ 3 
                 ))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...