很抱歉,因為我覺得這個問題的版本已被問過很多次,但我根本無法從其他示例中找到適用于這種情況的代碼。我有一列,我想要的所有資訊都存盤在兩組“%%”之間,我想在兩組括號之間提取這些資訊并將其放入一個新列中,在本例中稱為 df$empty .
這是一個很長的專欄,但在所有情況下,我只需要括號之間的資訊。有沒有辦法在整個專欄中對此進行編碼?
具體來說,我希望在此示例中有一個看起來像“資訊”、“通緝令”的新列。
empty <- c('NA', 'NA')
information <- c('notimportant%%information%%morenotimportant', 'ignorethis%%wanted%%notthiseither')
df <- data.frame(information, empty)
uj5u.com熱心網友回復:
在這種情況下你可以這樣做:
df$empty <- sapply(strsplit(df$information, '%%'), '[', 2)
# information empty
# 1 notimportant%%information%%morenotimportant information
# 2 ignorethis%%wanted%%notthiseither wanted
也就是說,將文本拆分為'%%'結果向量的第二個元素。
或者您可以使用以下方法獲得相同的結果sub():
df$empty <- sub('.*%%(. )%%.*', '\\1', df$information)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/535255.html
標籤:r细绳数据框特点提炼
