我想知道如何使用lapply和/或for循环来获得更简洁的代码。
这是我目前拥有的,它的工作原理。
MLFreq <- MLlyrics %>%
unnest_tokens(word, line) %>%
anti_join(stop_words) %>%
ungroup() %>%
count(word)
MLpct <- sum(albumList2$MLlyrics$n) / sum(MLFreq$n)
ViewFreq <- ViewLyrics %>%
unnest_tokens(word, line) %>%
anti_join(stop_words) %>%
ungroup() %>%
count(word)
Viewpct <- sum(albumList2$ViewLyrics$n) / sum(ViewFreq$n)
#... repeating 6 times with different data frames
我一直在努力
Freq <- lapply(albumList2, function(df){
df %>% unnest_tokens(word, line) %>%
anti_join(stop_words) %>%
ungroup()%>%
count(word) %>%
sum(albumList2$df$n) / sum(df$n)
})
和
for (i in 1:length(albumList2)) {
unnest_tokens(word, line) %>%
anti_join(stop_words) %>%
ungroup()%>%
count(word) %>%
print(sum(albumList2$i$n) / sum(i$n))
}
但是lapply带来了
Error in check_input(x) : Input must be a character vector of any length or
a list of character vectors, each of which has a length of 1.
而for循环带来了
no applicable method for 'unnest_tokens_' applied to an object of class
"function"
作为参考,albumList2包含数据框列表(MLlyrics,ViewLyrics等...)
我本来打算原样离开它,但只是读了一句“如果你使用相同的代码3次,循环它”