【问题标题】:Using lapply instead of repeating code使用 lapply 而不是重复代码
【发布时间】: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 的虚拟数据会很好。

标签: r loops lapply


【解决方案1】:

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。请添加一些虚拟数据,每个人都可以测试并更好地帮助您。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    • 2021-04-23
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 2017-12-19
    相关资源
    最近更新 更多