Вопрос

I want to change the type to factor of all variables in a data frame whose names match a certain pattern.

So here I am trying to change the type to factor of all variables whose name begins with namestub in the dataframe df.

attach(df)    
sapply(grep(glob2rx("namestub*"), names(df)), as.factor)

But this doesn't work since

> levels(df$namestub1)
NULL
Это было полезно?

Решение

## Make a reproducible example
df <- data.frame(namestubA = letters[1:5], B = letters[5:1], 
                 namestubC = LETTERS[1:5], stringsAsFactors=FALSE)

## Get indices of columns to convert
ii <- grep(glob2rx("namestub*"), names(df))

## Convert and replace the indicated columns
df[ii] <- lapply(df[ii], as.factor)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top