【发布时间】:2014-02-12 09:08:51
【问题描述】:
我想根据另一列中的字符串向 data.table 添加列。这是我的数据和我尝试过的方法:
参数 1:{客户ID:459;时间:1386868908703;版本:6} 2:{客户ID:459;编号:52a9ea8b534b2b0b5000575f;时间:1386868824339;用户:459001} 3:{客户ID:988;时间:1388939739771} 4:{客户ID:459;编号:52a9ec00b73cbf0b210057e9;时间:1386868810519;用户:459001} 5:{客户ID:459;时间:1388090530634}创建此表的代码:
DT = data.table(Params=c("{ clientID : 459; time : 1386868908703; version : 6}","{ clientID : 459; id : 52a9ea8b534b2b0b5000575f; time : 1386868824339; user : 459001}","{ clientID : 988; time : 1388939739771}","{ clientID : 459; id : 52a9ec00b73cbf0b210057e9; time : 1386868810519; user : 459001}","{ clientID : 459; time : 1388090530634}"))
我想解析“参数”列中的文本并根据其中的文本创建新列。例如,我希望有一个名为“user”的新列,它只包含 Params 字符串中“user:”之后的数字。添加的列应如下所示:
参数用户 1:{客户ID:459;时间:1386868908703;版本:6} 不适用 2:{客户ID:459;编号:52a9ea8b534b2b0b5000575f;时间:1386868824339;用户:459001} 459001 3:{客户ID:988;时间:1388939739771} 不适用 4:{客户ID:459;编号:52a9ec00b73cbf0b210057e9;时间:1386868810519;用户:459001} 459001 5:{客户ID:459;时间:1388090530634} 459001我创建了以下函数来解析(在本例中为“用户”):
myparse <- function(searchterm, s) {
s <-gsub("{","",s, fixed = TRUE)
s <-gsub(" ","",s, fixed = TRUE)
s <-gsub("}","",s, fixed = TRUE)
s <-strsplit(s, '[;:]')
s <-unlist(s)
if (length(s[which(s==searchterm)])>0) {s[which(s==searchterm)+1]} else {NA}
}
然后我使用下面的函数来添加一列:
DT <- transform(DT, user = myparse("user", Params))
这适用于包含在所有行中的“时间”,但不适用于仅包含在两行中的“用户”。返回以下错误:
Error in data.table(list(Params = c("{ clientID : 459; time : 1386868908703; version : 6}", :
argument 2 (nrow 2) cannot be recycled without remainder to match longest nrow (5)
我该如何解决这个问题?谢谢!
【问题讨论】:
标签: regex r parsing transform data.table