【问题标题】:perform gsub in a data frame with 2 columns在具有 2 列的数据框中执行 gsub
【发布时间】:2014-04-16 10:32:19
【问题描述】:

我有 2 列的数据集,我想使用 gsub 清理我的数据集,例如

Data_edited_txt2 <- gsub("(RT|via)((?:\\b\\W*@\\w+)+)", "", Data_edited_txt2$text)
Data_edited_txt2 <- gsub("@\\w+", " ", Data_edited_txt2$text)
Data_edited_txt2 <- gsub("[[:punct:]]", "", Data_edited_txt2$text) 

在第二次运行 gsub 时我会得到一个错误:“$ operator is invalid for atomic vectors”,我注意到在运行第一个 gsub 后第二列会消失。

请告知如何执行所有 gsub,但保留第 2 列?

structure(list(text = structure(c(1L, 3L, 7L, 4L, 2L, 5L, 6L), .Label = c("@airasia im searching job", 
"@AirAsia no flight warning for cebu outbound?", "@shazzr1 @AirAsia never mind.. now everyone can fly.", 
"@TigerAir confirmed as having far nastier policies and uncaring customer service than @airasia who I will now fly every time in preference.", 
"@Wingmates Since your taxes is HIGHER than other airlines but your service is really BAD because always change and cancel the flight.", 
"hai MASwings @Wingmates . Bilakah tempoh promosi anda? Saya ingin terbang ke Palawan dengan bajet yang agak rendah :3", 
"One thing I \"like\" about @AirAsia is, DELAY."), class = "factor"), 
created = structure(c(3L, 2L, 1L, 7L, 6L, 4L, 5L), .Label = c("2/2/2014 11:30", 
"2/2/2014 11:32", "2/2/2014 12:18", "24/2/2014 4:03", "29/3/2014 8:21", 
"30/1/2014 16:02", "31/1/2014 8:13"), class = "factor")), .Names = c("text", 
"created"), class = "data.frame", row.names = c(NA, -7L))

【问题讨论】:

  • 您将Data_edited_txt2$text 的替换向量分配给Data_edited_txt2,因此该对象现在仅由单个向量组成。相反,分配给Data_edited_txt2$text

标签: regex r string gsub text-extraction


【解决方案1】:

您覆盖整个数据框,而不是仅覆盖一列。试试这个:

Data_edited_txt2$text <- gsub("(RT|via)((?:\\b\\W*@\\w+)+)", "", Data_edited_txt2$text)
Data_edited_txt2$text <- gsub("@\\w+", " ", Data_edited_txt2$text)
Data_edited_txt2$text <- gsub("[[:punct:]]", "", Data_edited_txt2$text) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 2021-11-23
    • 2017-05-18
    相关资源
    最近更新 更多