Shawn Brar
Shawn Brar

Reputation: 1420

Change some column's classes to integer

I have a data.table as following :-

library(data.table)
a <- data.table(one = as.character(2011:2020), two = rep(2, times = 10),
                three = rep(3, times = 10), four = rep(4, times = 10),
                five = rep(5, times = 5))

I want to change the columns two, three and four to integer from numeric. Using the following code:-

a[, lapply(.SD, as.integer), .SDcols = colnames(a)[-c(1, 4)]]

they do change to integer, but this only returns columns two, three and four. Columns one and five are missing.

I want to know if there is a data.table way which can achieve this.

Thanks in advance.

Upvotes: 0

Views: 49

Answers (2)

akrun
akrun

Reputation: 886998

We can use dplyr

library(dplyr)
a %>%
   mutate(across(all_of(cols), as.integer))

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388862

You can use .SDcols in the following way -

library(data.table)

cols <- 2:4
#column names work as well
#cols <- c('two', 'three', 'four')

a[, (cols) := lapply(.SD, as.integer), .SDcols = cols]
a

#     one two three four five
# 1: 2011   2     3    4    5
# 2: 2012   2     3    4    5
# 3: 2013   2     3    4    5
# 4: 2014   2     3    4    5
# 5: 2015   2     3    4    5
# 6: 2016   2     3    4    5
# 7: 2017   2     3    4    5
# 8: 2018   2     3    4    5
# 9: 2019   2     3    4    5
#10: 2020   2     3    4    5

str(a)

#Classes ‘data.table’ and 'data.frame': 10 obs. of  5 variables:
# $ one  : chr  "2011" "2012" "2013" "2014" ...
# $ two  : int  2 2 2 2 2 2 2 2 2 2
# $ three: int  3 3 3 3 3 3 3 3 3 3
# $ four : int  4 4 4 4 4 4 4 4 4 4
# $ five : num  5 5 5 5 5 5 5 5 5 5
# - attr(*, ".internal.selfref")=<externalptr> 

Upvotes: 2

Related Questions