Changing values whose variable names contain cerntain pattern in R

Viewed 35
kal1a01 kal1b01 kal1c01 kal1a02 kal1b02 kal1c02
 1       2      -1      -2      -3      -4
-2      -2      1       -2      -1      -4

I would like to substitute the values with some characters as the following:

-1 = .a 
-2 = .b
-3 = .c
-4 = .d 

Therefore, I tried :

vars(stars_with("kal1")) = case_when(vars(stars_with("kal1")) == -1 ~ ".a",
                                         vars(stars_with("kal1")) == -2 ~ ".b",
                                         vars(stars_with("kal1")) == -3 ~ ".c",
                                         vars(stars_with("kal1")) == -4 ~ ".d")

However, I got the error:

Error in eval_tidy(pair$lhs, env = default_env) : 
  'list' object cannot be coerced to type 'double'

Why do I get this error and what can be the solution?

1 Answers

You have an incorrect syntax. Try this -

library(dplyr)

df %>%
  mutate(across(starts_with("kal1"), ~case_when(. == -1 ~ "a", 
                                               . == -2 ~ "b", 
                                               . == -3 ~ "c", 
                                               . == -4 ~ "d", 
                                               TRUE ~ as.character(.))))

#  kal1a01 kal1b01 kal1c01 kal1a02 kal1b02 kal1c02
#1       1       2       a       b       c       d
#2       b       b       1       b       a       d
Related