【发布时间】:2017-07-01 00:51:12
【问题描述】:
我在尝试使用以下函数获得正确输出时收到错误"Error in myData$ID1 : $ operator is invalid for atomic vectors"。由于某种原因,该函数没有继承列名,因此出现错误invalid for atomic vectors。
那么如何正确继承 colnames 以及如何修复此错误?
#HOW TO DO THIS WITH apply below?
myData <- data.table(ID1=c("1;11","2;22","3;33"),ID2=c("a;b","c;d",";"))
readMyRow <- function(myData, myIndex)
{
#TODO: Error is here because col names not inherited, why?
s3<- strsplit(myData$`ID1`, split=";")
s4<- strsplit(myData$`ID2`, split=";")
return(paste(s3[[myIndex]], s4[[myIndex]], sep=";"))
}
#Combine all rows
myData$Combined <- apply(myData, 1, readMyRow)
正确的输出
myData <- data.table(ID1=c("1;11","2;22","3;33"),ID2=c("a;b","c;d",";"))
s3<- strsplit(myData$`ID1`, split=";")
s4<- strsplit(myData$`ID2`, split=";")
paste(s3[[1]], s4[[1]], sep=";")
paste(s3[[2]], s4[[2]], sep=";")
paste(s3[[3]], s4[[3]], sep=";")
【问题讨论】:
标签: r function scope data.table multiple-columns