Skip to content
Prev 296244 / 398498 Next

Redefine multiple columns (using grep) as factor variables

Hi,

I have a dataframe with around 100 columns. Now I want
to redefine some of the columns as factors (using as.factor).
Luckily all the names of the columns I want to redefine start with 
"crast". Thus I thought I can use grep() for that purpose...
...I found an example for redefining a single column as factor
but that is not working with multiple columns I get from grep()...

what I tried so far:
df[, grep("^crast", colnames(df))] <- as.factor(df[, grep("^crast", colnames(df))])

any suggestions?

cheers,

/Johannes