R:使用sapply或str_replace_all而不是FindReplace



示例数据帧:

words <- c('Nothing', 'no thing', 'nada', 'nuthin', 'not a thing', 'nothing', 'nothing', 'Nothing', 'nil')
number <- c(1:9)
df <- data.frame(words, number)

在这个df中,我需要替换所有等价于";什么都没有";用";什么都没有";。在这个示例df中,这是所有的单词,但实际上df有许多不应该更改的单词。我有一个文本文件,里面有应该更改的单词列表,我使用read_delim读取了该文件。在中读取文件后,"changes"在通过typeof((运行后显示为"list",并显示为";spec_tbl_df"tbl_ df"tbl"data.frame";在通过类((运行之后。

我只能从DataCombine包中获得FindReplace。我首先在"changes"中创建了一个替换列,然后通过FindReplace运行它。

changes <- mutate(changes, Replacement='Nothing')
df <- FindReplace(df, 'words', changes, from='words', to='Replacement', exact=TRUE, vector=FALSE)

结果就是我想要的。

words    number
Nothing  1
Nothing  2
Nothing  3
Nothing  4
Nothing  5
Nothing  6
Nothing  7
Nothing  8
Nothing  9

但我认为应该有一种方法在"changes"上运行一个循环,并使用sapply或str_replace_all来实现这一点。但我不能让这两个都发挥作用。我一直得到错误:UseMethod中的错误("type"(:没有适用于"type"的方法应用于类"的对象;c('bl_df','tbl','data.frame'(";。如果可能的话,我想知道如何让这两种选择发挥作用。此外,如果您对DataCombine软件包有任何想法,我们将不胜感激。我以前从未碰到过它。

实现这一点的两种方法是使用嵌套的ifelse语句或替换表,然后使用left_join((。

嵌套ifelse的示例:您可以根据需要多次循环此项。

df %>%
mutate(col_with_text = ifelse(col_with_text == "Nothing", "None",
ifelse(col_with_text == "nada", "None", NA)) 

表和左联接的示例:

table_for_join <- data.frame(col_with_names = c('Nothing', 'no thing', 'nada', 'nuthin', 'not a thing', 'nothing', 'nothing', 'Nothing', 'nil'),
new_values = "None") # just made this one all the same for simplicity, but you can define this table however makes sense 
df %>%
mutate(new_col = left_join(., table_for_join))

您可以尝试这种方法

df2 <- df %>% 
mutate(words = str_replace_all(words, regex(" "), "")) %>% 
mutate(words =  str_to_title(words, locale = "en")) %>% 
mutate(words =  str_replace_all(words, regex("^Na.*|^Nu.*|^Nil.*|^Nota.*"), "Nothing"))
df2
#     words   number
# 1 Nothing      1
# 2 Nothing      2
# 3 Nothing      3
# 4 Nothing      4
# 5 Nothing      5
# 6 Nothing      6
# 7 Nothing      7
# 8 Nothing      8
# 9 Nothing      9

最新更新