R Convert Column Classes of Data Table (Example) | Numeric, Character & Factor | data.table Package

preview_player
Показать описание
R code of this video:

x2 = letters[6:2],
x3 = 9:5)
data # Print data table

sapply(data, class) # Check classes of data table columns

sapply(data_new1, class) # Check classes of data table columns

change_columns <- c("x1", "x3") # Specify columns to change

data_new2 <- data # Duplicate data table
data_new2[ , # Change class of certain columns
.SDcols = change_columns]

sapply(data_new2, class) # Check classes of data table columns

Follow me on Social Media:
Рекомендации по теме
Комментарии
Автор

Joachim,
Nice presentation. There is another shorter way to do this using the hablar package using convert()
For example, convert(data, fct(x1, x4), int(x2, x5), lgl(x6:x10). This will convert the columns shown to factor (fct), integer(int) and logical (lgl). This works well with pipes too (%>%). However, I am not sure if this will work for data.table which is designed differently than data frames. Finally, if you have a small dataset then there is no reason to use data.table which is designed for big data.

haraldurkarlsson
Автор

Hi Jochaim, I have a data frame with all of its columns as "lists". How do I change them to charracter. I can change them one by one but I have 165 columns!!

tmitra
Автор

I am getting this error Warning message:
In eval(jsub, SDenv, parent.frame()) : NAs introduced by coercion

ajetakrishnatre
Автор

Hi, Thanks a lot for your video!
I have a question. When doing as you say to convert a duration variable from 'difftime' class to numeric, I obtain this as an output (error code) for my input:

INPUT: corIEOnum <- corIEO[, "Duration" := as.numeric("Duration")]

OUTPUT: Error in `:=`("Duration", as.numeric("Duration")) :
Check that is.data.table(DT) == TRUE. Otherwise, := and `:=`(...) are defined for use in j, once only and in particular ways. See help(":=").

Could you help with the := error?
Thanks!!

bboyalexpourtj
Автор

Warning message:
In eval(jsub, SDenv, parent.frame()) : NAs introduced by coercion

ajetakrishnatre
Автор

My R Studio says...

could not find function ":="

leonardourbiola
Автор

Hi! Your videos have been super helpful! Is there a way to do selected multiple columns using mutate() and as.numeric() function? I know how to change one column from character to numeric using the following code:
clean_data <- clean_data %>% mutate(gender = as.numeric(gender))
However, I'm not sure if this is possible with the functions
Thanks :)

emiliegasnier