Hi R Masters,
I have following simple df:
df <- data.frame(
stringsAsFactors = FALSE,
URN = c("aaa", "bbb", "ccc"),
Q9a = c("Exellant", "!", "Honest"),
Q9b = c("x", NA, "Trustworthy"),
Q9c = c("Friendly", "Professional", NA)
)
I would like to recode all NAs and short characters into "Blank" and other into "Comment".
I know I can do it using this code:
library(dplyr)
library(stringr)
df <- df %>%
mutate(Q9a.Blank = case_when(is.na(Q9a) ~ 1,
str_length(Q9a) < 2 ~ 1),
Q9b.Blank = case_when(is.na(Q9b) ~ 1,
str_length(Q9b) < 2 ~ 1),
Q9c.Blank = case_when(is.na(Q9c) ~ 1,
str_length(Q9c) < 2 ~ 1))
df$Q9a.Blank <- recode_factor(df$Q9a.Blank, `1` = "Blank", .missing = "Comment")
df$Q9b.Blank <- recode_factor(df$Q9b.Blank, `1` = "Blank", .missing = "Comment")
df$Q9c.Blank <- recode_factor(df$Q9c.Blank, `1` = "Blank", .missing = "Comment")
But I am sure there is more elegant and much shorter code considering that all variables taken into account have ".Blank" in their names.
Can you help?