Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to convert many columns that are numeric to factor type. An example table:

df <- data.frame(A=1:10, B=2:11, C=3:12)

I tried with apply:

cols<-c('A', 'B')
df[,cols]<-apply(df[,cols], 2, function(x){ as.factor(x)});

But the result is a character class.

> class(df$A)
[1] "character"

How can I do this without doing as.factor for each column?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
628 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try

df[,cols] <- lapply(df[,cols],as.factor)

The problem is that apply() tries to bind the results into a matrix, which results in coercing the columns to character:

class(apply(df[,cols], 2, as.factor))  ## matrix
class(as.factor(df[,1]))  ## factor

In contrast, lapply() operates on elements of lists.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...