I am a self-taught programmer with a few years' experience in MATLAB. I'm brand new to R and this is my first question on Stack Overflow.
I am trying to recode multiple variables in a dataframe using recode
from dplyr. In the code below, I provide a snippet of data
and the list of options, opt_dass
, I want to use with recode
. I would like to convert the string values in each variable starting with "dass" to a number - Never = 0, Sometimes = 1, and so on.
I am aware that there are multiple approaches to this problem, including ifelse
, lapply
, and case_when
. In the below example, I am wondering why I am getting the error about a non-language object. I am using paste0
to create variable names to reference in data
. I've done a lot of reading about how to reference column names in a for
loop in R and I still haven't found the answer.
library(tidyverse)
data <- structure(list(id = c("1", "2", "3", "4", "5", "6", "7", "8",
"9", "11"), dass1_t1 = c("Sometimes", "Often", "Often", "Almost Always",
"Sometimes", "Sometimes", "Sometimes", "Sometimes", "Sometimes",
"Sometimes"), dass2_t1 = c("Sometimes", "Never", "Often", "Sometimes",
"Sometimes", "Never", "Sometimes", "Sometimes", "Often", "Sometimes"
), dass3_t1 = c("Often", "Sometimes", "Never", "Never", "Never",
"Sometimes", "Never", "Never", "Sometimes", "Sometimes"), dass4_t1 = c("Never",
"Never", "Never", "Never", "Never", "Sometimes", "Never", "Never",
"Never", "Sometimes"), dass5_t1 = c("Almost Always", "Sometimes",
"Never", "Sometimes", "Never", "Sometimes", "Sometimes", "Never",
"Almost Always", "Often")), row.names = c(NA, -10L), class = "data.frame")
opt_dass <- list("Never"=0,"Sometimes"=1,"Often"=2,"Almost Always"=3) # list - chr to num
# my attempt at a for loop to recode
for (i in 1:5) {
attach(data)
paste0("dass_", i, "_t1") <- recode(paste0("dass_", i, "_t1"), !!!opt_dass, .default=NA_real_)
}
#> Error in paste0("dass_", i, "_t1") <- recode(paste0("dass_", i, "_t1"), : target of assignment expands to non-language object
Created on 2020-11-04 by the reprex package (v0.3.0)
Bonus question: Is there a way to write one for
loop that could accomplish recoding for multiple sets of variables with different sets of options? I have a dataset with multiple self-report measures where different string responses have different numeric values. I think this would involve some metaprogramming and would love to hear your ideas!