[1] NA NA
[3] NA NA
[5] "kilo130.9" "kilo5075.69"
[7] "kilo465" "kilo34.8"
[9] "kilo607.195" "kilo1362.7"
上面是我从R复制粘贴的数据框的列 我运行下面的代码从列中删除单词kilo但它不起作用。我没有收到错误但它没有删除单词kilo。我使用下面的代码
stopwords = readLines('stopwords.txt') #I put the word kilo in this txt file
x = df$Dist
x = removeWords(x,stopwords)
df$newdist<-x
什么可能是共鸣?
答案 0 :(得分:1)
removeWords()
只会删除与"kilo"
完全匹配的字词(不包含其他字符):
x <- c("kilo", "kilo2", "pound")
tm::removeWords(x, "kilo")
#> [1] "" "kilo2" "pound"
这是另一种选择:
library("stringr")
x <- c(NA, NA, NA, NA, "kilo130.9", "kilo5075.69", "kilo465", "kilo34.8", "kilo607.195", "kilo1362.7")
str_replace(x, "kilo", "")
#> [1] NA NA NA NA "130.9" "5075.69" "465"
#> [8] "34.8" "607.195" "1362.7"
答案 1 :(得分:0)
以下是使用gsub
的基本R解决方案:
# Sample data
w <- c(
NA, NA,
NA, NA,
"kilo130.9", "kilo5075.69",
"kilo465", "kilo34.8",
"kilo607.195", "kilo1362.7")
# Strings that should be deleted
stopwords <- c("kilo", "something");
sapply(w, function(x)
x <- gsub(sprintf("(%s)", paste(stopwords, collapse = "|")), "", x));
# <NA> <NA> <NA> <NA> kilo130.9 kilo5075.69
# NA NA NA NA "130.9" "5075.69"
# kilo465 kilo34.8 kilo607.195 kilo1362.7
# "465" "34.8" "607.195" "1362.7"