鉴于此data.table
DT = data.table(item=c("item1 - description one", "item2 - description two", "item3 - description three"), sales=1:3)
DT
item sales
1: item1 - description one 1
2: item2 - description two 2
3: item3 - description three 3
如何轻松获得类似
的输出 code sales
1: item1 1
2: item2 2
3: item3 3
可能很容易,但提前谢谢。
答案 0 :(得分:1)
你可以这样做:
DT[, item:=gsub(item, pattern=" - [a-zA-Z ]+", replacement="")]
setnames(DT, "item", "code")
# code sales
#1: item1 1
#2: item2 2
#3: item3 3