I want to recode the following values < 4 = -1, 4 = 0, > 4 = 1 for the following variables defined by core.vars in the dataset, and still keep the rest of the variables in the data frame.
temp.df <- as.tibble (mtcars)
other.vars <- c('hp', 'drat', 'wt')
core.vars <- c('mpg', 'cyl', 'disp')
temp.df <- rownames_to_column (temp.df, var ="cars_id")
temp.df <- temp.df %>% mutate_if (is.integer, as.numeric)
I have tried a number of ways to implement this. Using case_when
, mutate
, recode
but with no luck. recode
requires a vector and so my thought was to create a vector using case_when
or mutate
for each variable of interest and then recoding the values. But they have failed.
temp.df <- temp.df %>%
mutate_at(.vars %in% (core.vars)), '< 4' = "-1", '4' = "0", '> 4' = "1")
Error: unexpected ',' in "temp.df <- temp.df %>% mutate_at(.vars %in% (core.vars)),"
temp.df <- temp.df %>%
mutate_at(vars(one_of(core.vars)), '< 4' = "-1", '4' = "0", '> 4' = "1")
Error in inherits(x, "fun_list") : argument ".funs" is missing, with no default
temp.df <- temp.df %>%
mutate (temp.df, case_when (vars(one_of(core.vars)), recode ('< 4' = "-1", '4' = "0", '> 4' = "1")))
Error in mutate_impl(.data, dots) : Column
temp.df
is of unsupported class data.frame
temp.df <- temp.df %>%
case_when (vars(one_of(core.vars)), recode ('< 4' = "-1", '4' = "0", '> 4' = "1"))
Error in recode.character(
< 4
= "-1",4
= "0",> 4
= "1") : argument ".x" is missing, with no default
temp.df <- temp.df %>% rowwise() %>% mutate_at(vars (core.vars),
funs (case_when (
recode(., '< 4' = -1, '0' = 0, '>4' = 1)
))) %>%
ungroup()`
Error in mutate_impl(.data, dots) : Evaluation error: Case 1 (
recode(mpg,
< 4= -1,
0= 0,
>4= 1)
) must be a two-sided formula, not a double. In addition: Warning message: In recode.numeric(mpg,< 4
= -1,0
= 0,>4
= 1) : NAs introduced by coercion
Previous questions on the forum include how to do this for individual variables, however as mentioned I have 100 variables and 300 samples so inputting them individually line by line is not an option.
Ideally, it would be nice to not create a separate data frame and then do join, or to create multiple separate variables as mutate would do.
I am sure there is a a for loop and/or ifelse method for this, but was trying to use tidyverse to achieve the goals. Any suggestions would be helpful.