I'm working on data from a survey with 50 questions and I need to make the responses numeric. So far I've been trying to use mutate_at
but after about 6 hours of wrestling with it this is the only thing I've produced that won't make an error message:
data %>%
mutate_at(vars(2:12),
function(x) recode(x,
"None'"=0,
"A little of the time"=1,
"Sometime"=2,
"Most of the time"=3,
"All the time"=4))
The results of this are useless for my purposes because all of the "None" responses are displayed as NA and apparently none of the responses are actually being recoded as numbers, just as strings named "1" "2" etc. If I use summary()
on any given variable it appears that none of these changes actually stick, since it produces something like
A little of the time 70
All the time 7
etc.
I am able to correctly recode a variable using this code:
data$variable <- as.numeric(recode(
data$variable,
"None'"=0,
"A little of the time"=1,
"Sometime"=2,
"Most of the time"=3,
"All the time"=4
))
I have the patience to copy-paste/edit this 50 times but something tells me that's not how you're supposed to do this. I literally started using R yesterday so if I broke a rule or something I'm sorry, I'll delete this post.
EDIT: reproducible example
library("dplyr")
rawdata <- read.csv('filenamet.csv', header = TRUE, sep = ",", na.strings="")
data <- rawdata[-262,-c(1:62,75:83)]
#rename columns
names(data) <- gsub("\\.", "", names(data))
names(data)
data <- dplyr::rename(data,
frustration = aFrustration,
sad = bSad,
guilt = cGuiltyselfblame,
worry = dWorried,
irritable = eIrritable,
fear = fFear,
angry = gAngry,
lonely = hLonely,
helpless = iHelpless,
hopeless = jHopeless,
anxious = kAnxious,
depressed = lDepressed
)
#recode responses
data %>%
mutate_at(vars(2:12),
~as.numeric(recode(.,
"None"=0,
"A little of the time"=1,
"Sometime"=2,
"Most of the time"=3,
"All the time"=4)))
#get sum of each row
data$totalscore <- rowSums(data[,c(2:12)],na.rm = TRUE)