views:

201

answers:

2

I am using a dataset w/variables that have very similar names. I have to apply the same functions to 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?

+2  A: 
## 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]) 
}
Eduardo Leoni
Thank you! I am working this out. Should vnames be a vector of the columns in the data.frame that those variable names (the q01_a...'s) are referencing?
Michael
> for(i in vnames){+  UNCA[,paste(i, ".F", sep='')] <- factor(UNCA[,i]) Error: unexpected input in:"for(i in vnames){¬"
Michael
@user335897 There was a mistake in my code. I forgot to add the "value=TRUE" to the grep statement, so it was giving us the column numbers instead of names. Should work now.
Eduardo Leoni
Eduardo, vnames is now a list of the 13 variables I am interested in making factors. //However, //for (i in vnames) {//    UNCA[,paste(i, ".F", sep='')] <- factor(UNCA[,i])// }//Still returns the same "Error:unexpected input" message. //
Michael
Eduardo, vnames is now a list of the 13 variables I am interested in making factors. However, for (i in vnames) {     UNCA[,paste(i, ".F", sep='')] <- factor(UNCA[,i]) } Still returns the same "Error:unexpected input" message.
Michael
@Michael If you copy and paste the code above into R it should work. Does UNCA exist? Not sure what is going on.
Eduardo Leoni
A: 

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[a-m]", 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.

John