0 votes
1 view
in R Programming by (5.3k points)

I have a sample data frame like below:

data <- data.frame(matrix(sample(1:40), 4, 10, dimnames = list(1:4, LETTERS[1:10])))

I want to know how can I select multiple columns and convert them together to factors. I usually do it in the way like data$A = as.factor(data$A). But when the data frame is very large and contains lots of columns, this way will be very time-consuming. Does anyone know of a better way to do it?

1 Answer

0 votes
by (25.3k points)
edited by

To coerce multiple columns of a data frame to factors, you can use the lapply function as follows:

> data <- data.frame(matrix(sample(1:40), 4, 10, dimnames = list(1:4, LETTERS[1:10])))

> data

   A  B  C  D  E  F  G  H  I  J

1  2 22 20 33  5 23 34 25 28  6

2  4  9 37 14 10 26 32 15 18  8

3 24 21 11 13  1 17 39 30 19 35

4 36 12 16 29 31 40 27 38  3  7

> cols <- c("A", "C", "D", "H")

> data[cols] <- lapply(data[cols], factor) 

> sapply(data, class)

        A         B         C         D         E         F         G         H         I         J 

 "factor" "integer"  "factor"  "factor" "integer" "integer" "integer"  "factor" "integer" "integer" 

If you want to explore more in R programming then watch this R programming tutorial for beginner:

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...