簡體   English   中英

R中的data.table中的條件字符串拆分

[英]Conditional string split in data.table in R

基於這個問題: 在data.table列中拆分文本字符串 ,我想知道是否有一種有效的方法可以根據行的內容有條件地拆分文本字符串。

假設我有下表:

Comments                  Eaten
001 Testing my computer   No
0026 Testing my fridge    No
Testing my car            Yes

我會這樣:

ID   Comments             Eaten
001  Testing my computer  No
0026 Testing my fridge    No
NA   Testing my car       Yes

NA是空的。

這在data.table中是否可行?

注釋應該有一個ID,但由於這是可選的,我只想提取ID,當且僅當注釋以數字開頭時。

這可以使用tidyrextract函數來完成,該函數允許您指定正則表達式模式:

tidyr::extract(dt, Comments, c("ID", "Comments"), regex = "^(\\d+)?\\s?(.*)$")
#     ID            Comments Eaten
#1:  001 Testing my computer    No
#2: 0026   Testing my fridge    No
#3:   NA      Testing my car   Yes

如果希望將提取的列轉換為更合理的類型,則可以添加參數convert = TRUE


另一個只使用base R和data.table的選項就是

dt[grepl("^\\d+", Comments),                     # check if start with ID (subset)
   `:=`(ID = sub("^(\\d+).*", "\\1",Comments),   # extract ID from comments
        Comments = sub("^(\\d+)", "",Comments))  # delete ID from Comments
]

雖然在這種情況下,tidyr語法似乎對我來說更容易一些。 也許有一種方法可以使用data.table的tstrsplit函數和一個花哨的tstrsplit正則表達式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM