lapply function and as.factor

Hallo R studio community,

my issue:

lapply(data[ ,c(85:99)],as.factor)

and then I want to save columns 85:99 as factors in data.

I am stucked, can anybody help me in this?
thanks!

Your code looks fine. What's the problem?

Maybe you didn't assign the result of the operation back to data? See below for a working example.

data <- data.frame(col1 = c("A", "B", "A", "B"),
                   col2 = c("C", "B", "A", "C"),
                   col3 = c("C", "C", "A", "B"),
                   stringsAsFactors = FALSE)

str(data)
#> 'data.frame':    4 obs. of  3 variables:
#>  $ col1: chr  "A" "B" "A" "B"
#>  $ col2: chr  "C" "B" "A" "C"
#>  $ col3: chr  "C" "C" "A" "B"

data[, 1:3] <- lapply(data[, 1:3], as.factor)

str(data)
#> 'data.frame':    4 obs. of  3 variables:
#>  $ col1: Factor w/ 2 levels "A","B": 1 2 1 2
#>  $ col2: Factor w/ 3 levels "A","B","C": 3 2 1 3
#>  $ col3: Factor w/ 3 levels "A","B","C": 3 3 1 2

Created on 2020-06-05 by the reprex package (v0.3.0)

Thank you very much, I was missing the assignment! problem fixed :slight_smile:

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.