结合名称向量中的数据帧 [英] Combine data frames from a vector of names

查看:54
本文介绍了结合名称向量中的数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我认为容易解决的问题,但是我没有找到解决方法.我有大量要按行绑定的数据帧.为了避免列出所有数据帧的名称,我使用"paste0"快速创建了数据帧名称的向量.问题是我无法使rbind函数从该名称向量中识别数据帧.更明确地:

I have an issue that I thought easy to solve, but I did not manage to find a solution. I have a large number of data frames that I want to bind by rows. To avoid listing the names of all data frames, I used "paste0" to quickly create a vector of names of the data frames. The problem is that I do not manage to make the rbind function identify the data frames from this vector of name. More explicitely:

df1 <- data.frame(x1 = sample(1:5,5), x2 =  sample(1:5,5))
df2 <- data.frame(x1 = sample(1:5,5), x2 =  sample(1:5,5))
idvec <- noquote(c(paste0("df",c(1,2))))
> [1] df1 df2

我想得到什么:

dftot <- rbind(df1,df2)
   x1 x2
1   4  1
2   5  2
3   1  3
4   3  4
5   2  5
6   5  3
7   1  4
8   2  2
9   3  5
10  4  1

dftot <- rbind(idvec)
>       [,1]  [,2] 
> idvec "df1" "df2"

推荐答案

如果全局环境中存在多个对象,且对象的模式为 df ,后跟数字,则一个选项是使用 ls 查找所有带有 pattern 参数的对象.用 mget 对其进行包装,以获取 list 中的值,我们可以使用 do.call 进行 rbind .

If there are multiple objects in the global environment with the pattern df followed by digits, one option is using ls to find all those objects with the pattern argument. Wrapping it with mget gets the values in the list, which we can rbind with do.call.

v1 <- ls(pattern='^df\\d+')
`row.names<-`(do.call(rbind,mget(v1)), NULL)

如果我们知道对象,则另一个选择是 paste ,以创建对象名称的向量,然后像以前一样进行操作.

If we know the objects, another option is paste to create a vector of object names and then do as before.

v1 <- paste0('df', 1:2)
 `row.names<-`(do.call(rbind,mget(v1)), NULL)

这篇关于结合名称向量中的数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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