Reputation: 829
I'm trying to use data.table rather data.frame(for a faster code). Despite the syntax difference between than, I'm having problems when I need to extract a specific character column and use it as character vector. When I call:
library(data.table)
DT <- fread("file.txt")
vect <- as.character(DT[, 1, with = FALSE])
class(vect)
###[1] "character"
head(vect)
It returns:
[1] "c(\"uc003hzj.4\", \"uc021ofx.1\", \"uc021olu.1\", \"uc021ome.1\", \"uc021oov.1\", \"uc021opl.1\", \"uc021osl.1\", \"uc021ovd.1\", \"uc021ovp.1\", \"uc021pdq.1\", \"uc021pdv.1\", \"uc021pdw.1\")
Any ideas of how to avoid these "\" in the output?
Upvotes: 1
Views: 1820
Reputation: 887971
The as.character
works on vector
s and not on data.frame/data.table
objects in the way the OP expected. So, if we need to get the first column as character
class, subset with .SD[[1L]]
and apply the as.character
DT[, as.character(.SD[[1L]])]
If there are multiple columns, we can specify the column index with .SDcols
and loop over the .SD
to convert to character
and assign (:=
) the output back to the particular columns.
DT[, (1:2) := lapply(.SD, as.character), .SDcols= 1:2]
DT <- data.table(Col1 = 1:5, Col2= 6:10, Col3= LETTERS[1:5])
Upvotes: 3