为列表的每个元素创建一个单独的变量 [英] Create a separate variable for each element of a list

查看:64
本文介绍了为列表的每个元素创建一个单独的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据帧列表,该列表是通过一次读取25个.csv文件生成的.我想取消列出数据框以开始空间分析.也就是说,我希望列表的每个元素都有单独的数据框.

I have a list of data frames, which was produced from reading in 25 .csv files at once. I would like to unlist the data frames to begin a spatial analysis. That is, I would like to have individual data frames for each element of the list.

我已经尝试过unlist(),但是它不会产生我想要的结果.我还尝试了使用lapply()的方法,但是会产生错误.这是我尝试过的:

I have tried unlist(), but it does not produce the result I want. I have also tried an approach with lapply(), but it produces an error. Here's what I've tried:

x <- 1:3
y <- 4:6

l <- lapply(1:2, function(x){data.frame(x, y)})

lapply(1:length(l), function(i){paste('df', i, sep = '') <- data.frame(l[[i]])})

问题似乎出在将数据框分配给粘贴的名称.用as.character()包装它并没有帮助.

The problem seems to be in assigning the data frame to the pasted name. Wrapping it with as.character() did not help.

这确实有效:

"df1" <- data.frame(l[[1]])

似乎问题出在我的paste()函数的输出中,但是输出中有str()'chr'.有什么想法可以使我的方法起作用吗?有没有一种更干净的方法来取消列出我的数据框?

It seems the problem is somewhere in the output of my paste() function, but the output has str() 'chr'. Any ideas how I can make my approach work? Is there a cleaner way to unlist my data frames?

推荐答案

一种方法:

list2env(setNames(l,paste0("df",seq_along(l))), envir = parent.frame()) 

尽管我会在@baptiste的建议为时已晚之前予以注意,并避免这样做. 为什么?因为在两天的时间内,您会发现自己被get()paste以及混乱的循环所困,试图一次将函数应用于所有数据集.如果将它们保留在列表中,则可以执行lapply(l,functionname).

Though I would heed @baptiste 's advice before it is too late and avoid doing this. Why? Because in two days time you'll find yourself trapped using get() and paste and messy loops to try to apply a function to all of your datasets at once. If you keep them in a list you can just do lapply(l,functionname).

这篇关于为列表的每个元素创建一个单独的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆