【发布时间】:2018-05-31 07:16:54
【问题描述】:
library(tidyverse)
library(stringr)
library(janitor)
word_count <- function(data, char_col) {
char_col <- enquo(char_col)
data %>%
select(!!char_col) %>%
mutate(char_col = str_remove_all(!!char_col, '[[:punct:]]')) %>%
mutate(char_col = str_split(!!char_col, ' ')) %>%
separate(char_col, into = paste0('col', 1:30), fill = 'right') %>%
select(-col1) %>%
gather(value = word) %>%
select(word) %>%
remove_empty(c('rows')) %>%
filter(word != '') %>%
mutate(word = str_to_lower(word)) %>%
group_by(word) %>%
summarize(freq = n()) %>%
arrange(desc(freq))
}
iris %>%
as.tibble() %>%
mutate(Species = str_c(Species, ' species')) %>%
word_count(Species)
此代码在函数外部按预期工作,但是当我在函数内部使用它时,它将返回每个单词和每个“非拆分”字符串的频率。
我认为这是我如何放置“!!”的问题运营商,但我无法通过与他们进行反复试验来解决这个问题。这也可能是一个lazyeval问题,我不确定如何解决。
我希望函数的输出与下面代码的输出相匹配。
iris %>%
as.tibble() %>%
mutate(Species = str_c(Species, ' species')) %>%
select(Species) %>%
mutate(Species = str_remove_all(Species, '[[:punct:]]')) %>%
mutate(Species = str_split(Species, ' ')) %>%
separate(Species, into = paste0('col', 1:30), fill = 'right') %>%
select(-col1) %>%
gather(value = word) %>%
select(word) %>%
remove_empty(c('rows')) %>%
filter(word != '') %>%
mutate(word = str_to_lower(word)) %>%
group_by(word) %>%
summarize(freq = n()) %>%
arrange(desc(freq))
【问题讨论】:
-
请在我收到
Error in remove_empty(., c("rows")) : could not find function "remove_empty"时添加library(janitor) -
会做,忘了那个。谢谢!
标签: r dplyr lazy-evaluation tidyr