@Jaap对此stackoverflow问题的回答
数据是这样的:
Name Text idx c_org
1: John Text contains MIT 1 MIT
2: Sussan some text with Stanford University 2 Stanford
3: Bill He graduated from Yale, MIT, Stanford. 3 MIT,Yale,Stanford
4: Bill some text 4
对于column c_org
,如果有多个值(如观察3所示),MIT,Yale,Stanford
则将第一个值MIT
作为列值。结果应如下所示:
Name Text idx NewOrg
1: John Text contains MIT 1 MIT
2: Sussan some text with Stanford University 2 Stanford
3: Bill He graduated from Yale, MIT, Stanford. 3 MIT
4: Bill some text 4
(请注意,在该c_org
列中,某些字段具有多个值,有些甚至为空。在预期输出中,如果只有一个值,则保留该值;如果有多个,则保留第一个值;如果为空,则保留为空)
我尝试了这个(但失败了):
DT[ , str_split(c_org, ",")[[1]][1]]
我猜很常见的一种数据是在一个字段中有多个值。怎么做呢data.table
?(或者如果解决方案比更好,则以其他方式data.table
)
我们可以使用sub
匹配模式,,
后接一个或多个字符(.*
),直到$
'c_org'列中字符串的结尾(),然后将其替换为''
。可以分配输出(:=
)以创建列'NewOrg',并将'c_org'分配为NULL。
DT[, NewOrg := sub(',.*$', '', c_org)][,c_org:= NULL]
DT
# Name Text idx NewOrg
#1: John Text contains MIT 1 MIT
#2: Sussan some text with Stanford University 2 Stanford
#3: Bill He graduated from Yale, MIT, Stanford. 3 MIT
#4: Bill some text 4
或data.tablev1.9.6+
中的另一个选项是tstrsplit
DT[, NewOrg := tstrsplit(c_org, ',', fill='')[[1]]][, c_org:= NULL]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句