Reputation: 148
How can I recode a column using a function that decides which name an old variable name is to be changed to, based on a passed argument?
library(sjstats) # has example data
library(tidyverse)
data(efc)
# Function to decide the name of the variable
decide_name <- function(c161sex) {
name <- case_when(
c161sex == 1 ~ "Male",
c161sex == 2 ~ "Female",
TRUE ~ "missing"
)
return(name)
}
Recode the variable dynamically depending on the returned value (each dataset will have 1 and only 1 value for the variable "c161sex")
efc_renamed <- efc %>%
rename(decide_name = e42dep)
Upvotes: 2
Views: 139
Reputation: 35584
What you need is recode()
, instead of rename()
.
recode_dynam <- function(var) {
recode(var, `1` = "Male", `2` = "Female", .default = "missing", .missing = "missing")
}
efc_recoded <- efc %>%
mutate(e42dep = recode_dynam(e42dep))
efc_recoded %>%
count(e42dep)
# e42dep n
# 1 Female 225
# 2 Male 66
# 3 missing 617
Upvotes: 3
Reputation: 887223
We could use case_when
fn <- function(nm) {
case_when(nm == 1 ~ "Male", nm == 2 ~ "Female")
}
efc_new <- efc %>%
mutate(e42dep = fn(e42dep))
-checking
> table(efc_new$e42dep)
Female Male
225 66
Upvotes: 2