我想知道如何使用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等...)
我本来打算原样离开它,但只是按照&#34的方式阅读;如果你使用相同的代码3次,那就循环它&#34;