Brigadeiro
Brigadeiro

Reputation: 2945

Assign (different) column classes over data.frame

I need to change column classes over my entire data.frame. Ideally looking for an apply solution, but open to tidyverse or other solutions as well.

Example data

set.seed(1)
d <- data.frame("numbers" = as.character(1:10),
                "letters" = letters[1:10],
                "boolean" = sample(c("T", "F"), 10, T),
                stringsAsFactors = F)

I would like to make the first column (numbers) numeric, the second column (letters) character, and the third column (boolean) logical.

Upvotes: 3

Views: 208

Answers (2)

akrun
akrun

Reputation: 886998

According to ?type.convert, the usage is

type.convert(x, ...)

x - a vector, matrix, array, data frame, or list.

So, we can directly apply the type.convert on the data.frame.

d <- type.convert(d, as.is = TRUE)
str(d)
#'data.frame':  10 obs. of  3 variables:
# $ numbers: int  1 2 3 4 5 6 7 8 9 10
# $ letters: chr  "a" "b" "c" "d" ...
# $ boolean: logi  TRUE FALSE TRUE TRUE FALSE TRUE ...

Or another option is type_convert from readr

library(readr)
type_convert(d)

Upvotes: 5

Ronak Shah
Ronak Shah

Reputation: 388862

One option without manually specifying class to convert is readr::parse_guess which automatically converts the vector to "best" type.

d[] <- lapply(d, readr::parse_guess)

str(d)
#'data.frame':  10 obs. of  3 variables:
# $ numbers: num  1 2 3 4 5 6 7 8 9 10
# $ letters: chr  "a" "b" "c" "d" ...
# $ boolean: logi  TRUE TRUE FALSE FALSE TRUE FALSE ..

Or in base R, we can use type.convert with as.is = TRUE.

d[] <- lapply(d, type.convert, as.is = TRUE)

Upvotes: 4

Related Questions