[英]How to replace single word line in multiple lines?
我有一些字符串的數據框。 有些行有一個單詞,我想用空白代替。 我能夠檢索到該詞,但是在替換它們時,我會收到警告消息
警告消息:在gsub(pattern = text [lengths(gregexpr(“ [[:::]] +”,text))==中:參數'pattern'的長度> 1,並且僅使用第一個元素
只有第一個單詞會被替換,其余單詞將保持原樣。 我想替換數據框中的所有單個單詞。
我正在使用的代碼如下。
text <- c("Because I could not stop for Death -",
"Word1",
"He kindly stopped for me -",
"Word2",
"The Carriage held but just Ourselves - ",
"word3",
"and Immortality")
gsub(pattern = text[lengths(gregexpr("[[:alpha:]]+", text)) == 1], "", text)
我期望低於輸出。
"Because I could not stop for Death -",
"He kindly stopped for me -",
"The Carriage held but just Ourselves - ",
"and Immortality"
一個簡單的邏輯索引就可以解決問題,因為您要保留的單詞似乎位於1、3、5,...等位置,即
text[c(TRUE, FALSE)]
#[1] "Because I could not stop for Death -" "He kindly stopped for me -"
#[3] "The Carriage held but just Ourselves - " "and Immortality"
a=gsub("^\\w+$","",text)
[1] "Because I could not stop for Death -" ""
[3] "He kindly stopped for me -" ""
[5] "The Carriage held but just Ourselves - " ""
[7] "and Immortality"
grep("\\w",a,value = T)
[1] "Because I could not stop for Death -" "He kindly stopped for me -"
[3] "The Carriage held but just Ourselves - " "and Immortality"
或者你可以簡單地做
grep("\\w+\\s",text,value = T)
[1] "Because I could not stop for Death -" "He kindly stopped for me -"
[3] "The Carriage held but just Ourselves - " "and Immortality"
您能否嘗試遵循並讓我知道這是否對您有幫助。
text <- c("Because I could not stop for Death -",
"Word1",
"He kindly stopped for me -",
"Word2",
"The Carriage held but just Ourselves - ",
"word3",
"and Immortality")
獲取OP所需輸出的代碼:
text[!grepl("[Ww]ord[0-9]+", text)]
輸出如下。
[1] "Because I could not stop for Death -" "He kindly stopped for me -"
[3] "The Carriage held but just Ourselves - " "and Immortality"
對於來自幫助頁面的grepl
:
grepl返回邏輯向量(是否匹配x的每個元素)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.