【发布时间】:2017-12-16 02:50:05
【问题描述】:
我想知道如何使用 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 次,循环遍历它”的内容
【问题讨论】:
-
你能给出一个示例数据集吗?我想帮忙,但如果有一些使用
dput的虚拟数据会很好。