简体   繁体   中英

Modify data.table column class within a function

I am passing column names as strings into a function and wish to change the class of the corresponding column. Currently, I reference the column of the data.table using get(varName).

I have a data.table with a factor column that I wish to convert to character. Sample data:

dt <- data.table(factor(c("b","c")),foo=c(4,2))
sapply(dt, class)

Simplified attempt:

fo2 <- function(data, change){
  data[,get(change):=as.character(get(change))]
  return(data)
}

fo2(data=dt, change="V1")

Error in get(change) : object 'V1' not found

Thanks for any help understanding.

You don't need to use get on the left hand side. You could change your function to:

fo2 <- function(data, change){
  data[, (change) := as.character(get(change))][]
}

And with your example data, it looks like this:

dt <- data.table(factor(c("b","c")),foo=c(4,2))
sapply(dt, class)
#       V1       foo 
# "factor" "numeric" 
fo2(data=dt, change="V1")
#   V1 foo
#1:  b   4
#2:  c   2
str(dt)
#Classes ‘data.table’ and 'data.frame': 2 obs. of  2 variables:
# $ V1 : chr  "b" "c"
# $ foo: num  4 2
# - attr(*, ".internal.selfref")=<externalptr> 

I believe this would do it:

dt <- data.table(factor(c("b","c")),foo=c(4,2),char=c("X","Y"))

change <- c("V1", "char")

dt[, change] <- dt[, lapply(.SD, as.character), .SDcols = change]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM