Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 使用lappy而不是重复代码_R_Loops_Lapply - Fatal编程技术网

R 使用lappy而不是重复代码

R 使用lappy而不是重复代码,r,loops,lapply,R,Loops,Lapply,我想知道如何使用lappy和/或for循环来获得更简洁的代码 这就是我目前所拥有的,而且很有效 MLFreq <- MLlyrics %>% unnest_tokens(word, line) %>% anti_join(stop_words) %>% ungroup() %>% count(word) MLpct <- sum(albumList2$MLlyrics$n) / sum(MLFreq$n) ViewFreq <- ViewLyrics

我想知道如何使用lappy和/或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
但这一套带来了

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包含数据帧列表(MLLyps、ViewLyps等)


我本来打算让它保持原样,但只是按照“如果您使用相同的代码3次,请循环它”的思路阅读一些内容。

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

此外,这类引用:
sum(albumList2$df$n)/sum(df$n)
print(sum(albumList2$i$n)/sum(i$n))
不起作用

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


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

您能给出一个示例数据集吗?我很想提供帮助,但是如果能使用
dput
获得一些虚拟数据就好了。
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.
no applicable method for 'unnest_tokens_' applied to an object of class 
"function"