简体   繁体   中英

Creating a loop in R to apply the same functions to many similarly named variables

I am using a dataset with variables that have very similar names. I have to apply the same functions to all 13 variables at a time and I'm trying to shorten the code, instead of doing each variable individually.

q01a.F=factor(q01a)
q01b.F=factor(q01b)
q01c.F=factor(q01c)
q01d.F=factor(q01d)
q01e.F=factor(q01e)
q01f.F=factor(q01f)
q01g.F=factor(q01g)
q01h.F=factor(q01h)
q01i.F=factor(q01i)
q01j.F=factor(q01j)
q01k.F=factor(q01k)
q01l.F=factor(q01l)
q01m.F=factor(q01m)

Suggestions?

## suppose dnow is the data.frame with your variables of interest
dnow <- data.frame(q01a=rep(1,10), q01b=rep(2,10), q01c=rep(3,10), q02=rlnorm(10))
## we need to extract the variable names we need
## (they start with q01 and end with a, b or c
## dnow is your data.frame
vnames <- grep("^q01[a-c]", names(dnow), value=TRUE) ## regular expression matching the names
for (i in vnames) {
    dnow[,paste(i, ".F", sep='')] <- factor(dnow[,i]) 
}

It sounds like you're just beginning here, so a general tip. In order to work with the provided solution you would be wise to unpack it. names(dnow) has a results, look at it by itself. grep("^q01[am]", names(dnow)) also has a result that you should look at by itself. These could all have been on different lines and saved in additional variables in case you need that to make it more readable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM