1

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.

Michael Davidson
  • 1,391
  • 1
  • 14
  • 31
  • This tutorial-style answer might also be helpful: http://stackoverflow.com/q/15790743/1191259 – Frank Feb 20 '16 at 01:51

2 Answers2

3

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> 
talat
  • 68,970
  • 21
  • 126
  • 157
  • 1
    Or like `set(DT, j=change, v=as.character(DT[[change]]))`. It may be fugly for interactive use to those not used to it, but the OP is going to toss it into a function. – Frank Feb 20 '16 at 01:45
0

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]
Emil Lykke Jensen
  • 389
  • 1
  • 3
  • 18