I'm pretty new to R and not sure how to find variables based on its' values and then turn them into numeric.
I have looked at How do I change a value coded as "Yes" to a value of 1 in R? and Convert data.frame column format from character to factor.
These are my examples. I'm basically converting character variables that have only 'N' and 'Y' to 0 and 1, respectively. After going through some of the variables individually, I was wondering if there's a faster way to solve this problem. There are obviously other character variables that do not have "Y"/"N" so I don't want to just find all character variables and convert them into numeric. Please let me know if you have any ideas!
My codes:
df$var3<- ifelse(df$var3=="Y",1,0)
df$var4<- ifelse(df$var4=="Y",1,0)
df$var6<- ifelse(df$var5=="Y",1,0)
df$var7<- ifelse(df$var1=="Y",1,0)
sample df (pre):
n = c(2, 3, 5, 8, 10)
var1 = c("aa", "bb", "cc", "dd", "ee")
var2 = c(TRUE, FALSE, TRUE, TRUE, TRUE)
var3 = c("Y", "N", "Y", NA, "N")
var4 = c("Y", "N", "Y", NA, "Y")
var5 = c("aa", "bb", "cc", "dd", "ee")
var6 = c("Y", "N", "Y", "Y", "N")
var7 = c("Y", "N", "Y", "N", "N")
df = data.frame(n, var1, var2, var3,var4,var5,var6,var7)
df <- data.frame(lapply(df, as.character), stringsAsFactors = FALSE)
sample df (post, what I want):
n = c(2, 3, 5, 8, 10)
var1 = c("aa", "bb", "cc", "dd", "ee")
var2 = c(TRUE, FALSE, TRUE, TRUE, TRUE)
var3 = c("1", "0", "1", NA, "0")
var4 = c("1", "0", "1", NA, "1")
var5 = c("aa", "bb", "cc", "dd", "ee")
var6 = c("1", "0", "1", "1", "0")
var7 = c("1", "0", "1", "0", "0")
df = data.frame(n, var1, var2, var3,var4,var5,var6,var7)