I cannot find an answer to this specific question. I would like to recode multiple character columns into numeric columns. (It is a hundred columns) But:
So, I do not think I can use a range of column indexes. However, the columns I wish to recode start with the same column name prefix. I would like to recode any "Yes" to 1, "No" to 0, and blanks to NA.
I could do this manually one column at a time with the below code:
#Recode columns one at a time
library(car)
#skip ID column
#Skip Date column
df$Q1<-as.numeric(as.character(recode(df$Q1,"NA=NA; 'No'=0; 'Yes'=1; ''=NA")))
df$Q2<-as.numeric(as.character(recode(df$Q2,"NA=NA; 'No'=0; 'Yes'=1; ''=NA")))
#skip Q2.Explanation column
#do the above for a hundred more columns...
But I would like to recode a hundred, specific columns at the same time. Also these columns are separated by columns I do not wish to recode.
My data is below. Not sure what is dput:
ID<-c(01,02,03,04,05)
Q1<-c("Yes", NA,"", "No",NA)
Q1.Explanation<-c (NA, NA,"","Respondent did not get the correct answer", NA)
Q2<-c("No","Yes","Yes","", NA)
Q2.Explanation <-c("The right answer was not proven", NA, NA, NA, NA)
Q3<-c("", NA, "Yes", NA, NA)
Mydata<-as.data.frame(cbind(ID,Q1,Q1.Explanation, Q2, Q2.Explanation,Q3))
If you know that the columns you want to change always have the same names, just different locations in the table, then you can use regex on the column names to subset, then change the values in the columns with apply()
.
your_data[, grep("Q", colnames(your_data))] <- as.data.frame(apply(your_data[, grep("Q", colnames(your_data))],
2,
function(x) recode(x, "NA = NA; 'No' = 0; 'Yes' = 1; '' = NA")))
This should recode all of your columns that begin with "Q" regardless of their location any given month.