I'm new to R. I want to recode the same variable through multiple data frames. But I keep getting errors. Please see the following example of 3 small data frames. I want to create a new variable in each of the 3 dfs called Q2_nom that is recoded as "1" or "0" if Q2 is greater or less than the mean(Q2). Please see my code below.
df1:
Q1 <- c('ABC','DEF','GHI', 'DEF','JKL','XYZ')
Q2 <- c(21000, 23400, 26800, 26000, 20400, 30800)
df1 <- data.frame(Q1, Q2)
df2:
Q1 <- c('DEF','JKL','XYZ', 'ABC', 'MNO', 'PQR')
Q2 <- c(30100, 20200, 15800, 21000, 23400, 26800)
df2 <- data.frame(Q1, Q2)
df3:
Q1 <- c('ABC','DEF','GHI', 'XYZ', 'MNO', 'PQR')
Q2 <- c(17800, 23060, 13080, 27000, 22400, 26500)
df3 <- data.frame(Q1, Q2)
a <- c("Q1", "Q2", "Q3")
for (i in a) {
newname <- paste(i)
newname$Q2_mean_nom <- ifelse(newmame$Q2 > mean(newname$Q2, na.rm = TRUE), "1", "0")
}
I noticed that in doing the above, newname is not a df and so the mean won't run. Is there a way to make the loop recognise newname as a df?
I tried using a list but it didn't work either.
newlist <- c(df1, df2, df3)
for (i in 1:length(newlist)) {
newlist[[i]]$Q2_mean_nom <- ifelse(newlist[[i]]$Q2 > mean(newlist[[i]]$Q2, na.rm = TRUE),
"1", "0")
}
Please help. Thank you very much!