so I have some trouble again with writing basically a Syntax.
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
I have this command, which actually used to work. (For the example it's not complete, but what I'm trying to do should be clear. Apparently, there is a problem with the 18:31 command.
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 == 18:31 ~ 3,
TRUE ~ NA_real_))
For whatever reason though, it now gives me a warning message (I need to roughly translate since my R Studio is set to german and I actually can't find this error message anywhere). It still creates the xxx variable, though just some rows are being transformed while others, even with full information from the rest get assigned a "NA".
Warning message is (translated roughly from German):
Length of the longer vector is not a multiple of the shorter vector.
How can I rewrite the xx == 18:31 part, so it works?
Thank you in advance and sorry for the previous confusion.
Try this:
bsp1 %>%
mutate(xxx =
case_when(
(Geschlecht == "w") & (Alter > 18) & (xx == 55) ~ "1",
(Geschlecht == "m") & (Alter > 18) & (xx == 56) ~ "2",
TRUE ~ "NA_real_"))
Note that no elements meet the conditions, so you will all have all NA_real_
If you want a column with NA
remove all double quotes:
bsp1 %>%
mutate(xxx =
case_when(
(Geschlecht == "w") & (Alter > 18) & (xx == 55) ~ 1,
(Geschlecht == "m") & (Alter > 18) & (xx == 56) ~ 2,
TRUE ~ NA_real_))