R: loop through list
You can do this with simple assignment operators -- there's no need for a loop (as is usually the case in R). First, I'll construct a sample data frame, with your variables stored as the character type instead of as factors:
dat <- data.frame(id=1:2, ID_I=c("Agree", "Strongly Disagree"), IG_I=c("Strongly Disagree", "Agree"), stringsAsFactors=FALSE)
dat
# id ID_I IG_I
# 1 1 Agree Strongly Disagree
# 2 2 Strongly Disagree Agree
Now you can use column indexing to replace "Strongly Disagree" with 1:
cols <- c("ID_I", "IG_I")
dat[,cols][dat[,cols] == "Strongly Disagree"] <- 1
dat
# id ID_I IG_I
# 1 1 Agree 1
# 2 2 1 Agree
teeglaze
Updated on August 04, 2020Comments
-
teeglaze almost 4 years
I've come over this problem a few times by now, and this time I am eager to get an efficient solution. The underlying problem is that I want to loop through a list of variables with the
paste
function.dat <- read.csv("some file", header=TRUE) list.R <- c("IC","IG","DM","IM","IN","EN","RM") for (RO in list.R){ paste("dat$",RO,"_I", sep="")[ paste("dat$",RO,"_I", sep="") == "Strongly disagree"] <- 1 }
I pasted the name of the variable together, but this gives me a string in block quotes. I've tried the following but nothing worked so far:
eval(parse(text=paste("dat$",RO,"_I", sep="")))
or
get(paste("dat$",RO,"_I", sep=""))
do you know how to solve this so that the loop works? I would very much appreciate your help :)
(I know in this case I could also use
as.numeric(levels(dat$IC_I))[dat$IC_I]
but the order of the levels is wrong)