使用lapply而不是重复代码

问题描述 投票:-1回答:1

我想知道如何使用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次,循环它”

r loops lapply
1个回答
0
投票

lapply示例的问题是您循环的列表是嵌套列表而不是单个列表。

此外,参考类型:sum(albumList2$df$n) / sum(df$n)print(sum(albumList2$i$n) / sum(i$n))将无法正常工作。

i只是一个从1到长度的数字(albumList2)。说你想要$ 1 n或者albumList2 $ 1 $ n没有意义。

您应该阅读列表和嵌套列表herehere中的索引。请添加一些虚拟数据,每个人都可以测试并帮助您更好。

© www.soinside.com 2019 - 2024. All rights reserved.