在任意长的对象列表上使用 cbind [英] Using cbind on an arbitrarily long list of objects

查看:24
本文介绍了在任意长的对象列表上使用 cbind的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到一种方法,通过使用 cbind() 将许多单独的对象连接在一起来创建 data.frame.例如,如果 A、B、C &D都是等长的向量,可以用

I would like to find a way to create a data.frame by using cbind() to join together many separate objects. For example, if A, B, C & D are all vectors of equal length, one can create data.frame ABCD with

ABCD <- cbind(A,B,C,D)

但是,当要组合的对象数量变大时,将它们的所有名称都打出来就变得乏味了.此外,有没有办法在对象名称的向量上调用 cbind(),例如

However, when the number of objects to be combined gets large, it becomes tedious to type out all of their names. Furthermore, Is there a way to call cbind() on a vector of object names, e.g.

objs <- c("A", "B", "C", "D")
ABCD <- cbind(objs)

或者在包含所有要组合的对象的列表上,例如

or on a list containing all the objects to be combined, e.g.

obj.list <- list(A,B,C,D)
ABCD <- cbind(obj.list)

目前,我能想到的唯一解决方法是使用paste()cat()write.table(),和 source() 构造 cbind() 的参数,将其编写为脚本并获取它.这似乎是一个非常讨厌的混搭.另外,我已经研究了 do.call() 但似乎无法找到一种方法来完成我想要的.

Currently, the only workaround I can think of is to use paste(), cat(), write.table(), and source() to construct the arguments to cbind(), write it as a script and source it. This seems like a very nasty kludge. Also, I have looked into do.call() but can't seem to find a way to accomplish what I want with it.

推荐答案

do.call 函数在这里非常有用:

The do.call function is very useful here:

A <- 1:10
B <- 11:20
C <- 20:11

> do.call(cbind, list(A,B,C))
      [,1] [,2] [,3]
 [1,]    1   11   20
 [2,]    2   12   19
 [3,]    3   13   18
 [4,]    4   14   17
 [5,]    5   15   16
 [6,]    6   16   15
 [7,]    7   17   14
 [8,]    8   18   13
 [9,]    9   19   12
[10,]   10   20   11

这篇关于在任意长的对象列表上使用 cbind的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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