Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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_List_Lapply - Fatal编程技术网

r:lappy,但具有动态命名

r:lappy,但具有动态命名,r,list,lapply,R,List,Lapply,假设我在一个列表中有5个数据集(每个数据集名为df_1,df_2,等等),每个数据集都有一个名为cons的变量。我想在列表中的每个数据集中的cons上执行一个函数,并创建一个新变量,其名称具有相应数据集的后缀 因此,df_1最终将有一个名为cons_1的变量,df_2将有一个名为cons_2的变量。我遇到的问题是变量循环和试图创建动态名称 有什么建议吗?这其实很简单: df_names <- paste("df", 1:5, sep = "_") cons_names <- past

假设我在一个列表中有5个数据集(每个数据集名为
df_1
df_2
,等等),每个数据集都有一个名为
cons
的变量。我想在列表中的每个数据集中的
cons
上执行一个函数,并创建一个新变量,其名称具有相应数据集的后缀

因此,
df_1
最终将有一个名为
cons_1
的变量,
df_2
将有一个名为
cons_2
的变量。我遇到的问题是变量循环和试图创建动态名称


有什么建议吗?

这其实很简单:

df_names <- paste("df", 1:5, sep = "_")
cons_names <- paste("cons", 1:5, sep = "_")

for (i in 1:5) {
  # get the df from the current env by name
  df_i <- get(df_names[i])
  # do whatever you need to do and assign the result
  df_i[[cons_names[i]]] <- some_operation(df_i)
}

使用purrr包,这将是一个替代解决方案:

library(purrr)
lst <- list(mtcars_1 = mtcars,
            mtcars_2 = mtcars,
            mtcars_3 = mtcars,
            mtcars_4 = mtcars,
            mtcars_5 = mtcars)

map(seq_along(lst), function(x) {
lst[[x]][paste0("mpg_", x)] <- some_operation(lst[[x]]['mpg']); lst[[x]]
})
库(purrr)

第一步,我的建议是
do.call(rbind,List\o\u DFs)
。如果没有一个更具体的例子,我不知道任何人都可以提供更具体的想法。如果没有一个可复制的例子,我无法提供准确的答案,但类似的方法会起作用:
myList我需要得到的每个变量都有一个不同的名称。我的数据集基本上是相同的,100人对5部不同的电影进行评分,数据是堆叠的,而不是很宽。@vashts85我发现我误解了你的问题。我会澄清的。但是我还是不明白为什么不能把所有的数据框都列在一个列表中。@vashts85您应该创建一个具体的示例,包含可复制的输入和所需的输出,并将其添加到您的问题中,以避免此类误解。
library(purrr)
lst <- list(mtcars_1 = mtcars,
            mtcars_2 = mtcars,
            mtcars_3 = mtcars,
            mtcars_4 = mtcars,
            mtcars_5 = mtcars)

map(seq_along(lst), function(x) {
lst[[x]][paste0("mpg_", x)] <- some_operation(lst[[x]]['mpg']); lst[[x]]
})