R: loop list

I have already encountered this problem several times, and this time I really want to get an effective solution. The main problem is that I want to iterate over a list of variables using 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 inserted the variable name together, but that gives me a string in quotation marks for blocks. I tried the following but nothing worked:

 eval(parse(text=paste("dat$",RO,"_I", sep=""))) 

or

 get(paste("dat$",RO,"_I", sep="")) 

Do you know how to solve this to make the loop work? I would really appreciate your help :)

(I know that in this case I could also use as.numeric(levels(dat$IC_I))[dat$IC_I] but the order of the levels is incorrect)

+6
source share
1 answer

You can do this with simple assignment operators - there is no need for a loop (as is usually the case in R). First, I will create a sample data, with your variables stored as a character type, and not 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 
+10
source

Source: https://habr.com/ru/post/973292/


All Articles