无法替换data.table中特定列的值

时间:2018-05-09 05:31:30

标签: r data.table

我正在研究内部具有不同类型数据的数据集。当尝试进行一些替换时,例如将空值(“”)替换为NA,错误消息显示。

> xDT1[xDT1==""]<- NA
Error in as.POSIXlt.character(x, tz, ...) : 
  character string is not in a standard unambiguous format

主要与as.POSITct等有关。所以我试图选出正确的列,然后进行替换。元素是正确的,但组合(链)显示错误消息。 我尝试了其他帖子建议的sapply,lapply方法,但我认为问题在于如何传递值,而不是apply函数。 仍感到困惑。 请指教,非常感谢。

library(data.table)
library(magrittr)
xDT1 <- data.table(date=as.POSIXct(paste0("2018-1-",sep=1:12)),SN=1:12, Val=rnorm(12) ,  # simulation of date, SN, and Value
                           Tag1=factor(rep(letters[4:6],2)),Tag2=factor(rep(LETTERS[9:11],2)))   # simulation of tags

xDT1[3,4] <- ""   # arbitrarily assign empty value 
xDT1[7,5] <- ""   # arbitrarily assign empty value

xDT1str <- lapply(xDT1,class) %>% unlist;xDT1str         # get the class of each column
xWch1 <- names(xDT1str[which(xDT1str=="factor")])        # get the colnames of the "factorized" columns
xDT1[xDT1==""]<- NA                                      # Failed as described
xDT1[,.SD,.SDcols=xWch1]                                 # worked
xDT1[,.SD,.SDcols=xWch1]==""                             # worked
xDT1[,.SD,.SDcols=xWch1][xDT1[,.SD,.SDcols=xWch1]==""] <- NA  #Failed when chained. 

错误消息是,

> xDT1[,.SD,.SDcols=xWch1][xDT1[,.SD,.SDcols=xWch1]==""] <- NA
Error in `[<-.data.table`(`*tmp*`, , .SD, .SDcols = xWch1, value = list( : 
  unused argument (.SDcols = xWch1)

0 个答案:

没有答案