Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign (different) column classes over data.frame

Tags:

r

dplyr

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.

like image 895
Brigadeiro Avatar asked Feb 06 '26 09:02

Brigadeiro


1 Answers

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)
like image 194
akrun Avatar answered Feb 09 '26 01:02

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!