1

If I have a data.frame call MyDF with 108 variables and I want to apply factor(MyDF[, OnColumns 8 to 100]. How would I do this?

So in pseudocode:

for(i=8, i < 101, i++)
{
    # apply factor() to each column from 8 to 100
    factor( MyDF[,i] )
}

Does that make sense?

gung - Reinstate Monica
  • 11,583
  • 7
  • 60
  • 79
Gordon
  • 73
  • 7
  • 1
    see [this answer](http://stackoverflow.com/a/9252447/4137985) of [this question](http://stackoverflow.com/questions/9251326/convert-data-frame-column-format-from-character-to-factor) – Cath May 26 '16 at 14:02

1 Answers1

5

You can create a vector with the columns that need to be converted to factor and use lapply to iterate factor over those columns

tofactors <- 8:100
df[,tofactors] <- lapply(df[,tofactors], factor)
Sotos
  • 51,121
  • 6
  • 32
  • 66
  • Thats did the trick but I expected the values to be converted from 2 and 3 to 0 and 1 but they were not. They now have 2 levels ?but the values are 2 and 3 , how can I convert to 0s and 1s – Gordon May 26 '16 at 12:32
  • @Gordon Why would you want to change the levels of the factors? There is no value in doing that anyway. – Sotos May 26 '16 at 12:51
  • 1
    @Gordon what you are seeing are actually the labels. R stores factors as positive integers, so their actual values are 1 and 2. You can probably feed `factor` the 0 and 1 labels with the label argument. – lmo May 26 '16 at 12:56
  • So the original vector had 3 factors 0,1,2 corresponding to no answer, no and yes. I then changed the no answers to NAs and ran factor on the vector to re factor with two factors. I need the 2 factors to be binary 0 and 1 so I ran use in a logistic regression model – Gordon May 26 '16 at 13:36