在R中,如何轻松地将多个向量组合成数据帧? [英] In R, how to easily combine many vectors into a dataframe?

查看:576
本文介绍了在R中,如何轻松地将多个向量组合成数据帧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我知道我可以使用data.frame命令将多个向量组合成一个数据帧,如下所示:

  my.data<  -  data.frame(name1,age1,name20,age20,name38,age38)

(我知道,变量名没有什么意义,为什么要在三个不同的列中使用name1,name20和name38?请忽略:我的实际变量名不同 - 这只是为了说明的目的)。



问题是,我有大约40个这样的向量,我必须在我的代码的其他部分组合许多向量。所以我每次都不要复制粘贴一大堆代码是很方便的。所以我想到写这个循环:

  for(i in c(name,age hgt)
{
for(k in c(1,20,38))
{
my.data $ i,as.character(k)< - data.frame(get(paste(i,as.character(k),sep =)))
}
}

但这不行。这是因为我应该写一些这个代码的粘贴(),还是这个方法来解决这个问题呢?循环通过i和k的正确方式是什么,并获得一个newdata数据帧作为附加所有向量的最终结果?

解决方案
  name1<  - 字母[1:10] ] 
age1< - 1:10
name20< - letters [11:20]
age20< - 11:20
name38< - LETTERS [1:10 ]
age38< - 21:30

paste.pattern< - paste(rep(c(name,age),times = 3),
rep(c(1,20,38),each = 2),sep =)

newdata< - data.frame(sapply(paste.pattern,get))


So, I know that I can use the data.frame command to combine multiple vectors into one dataframe, like so:

my.data <- data.frame(name1, age1, name20, age20, name38, age38)

(I know, the variable names don't make much sense, why would I want name1, name20 and name38 in three different columns? Please ignore that: my actual variable names are different -- this is only for illustration purposes).

Problem is, I have about 40 of such vectors, and I have to combine many vectors in other parts of my code as well. So it would be convenient for me not to copy-paste a huge chunk of code every time. So I thought of writing a for loop around this:

for (i in c("name", "age", "hgt"))
{
    for (k in c(1,20,38))
    {
    my.data$i,as.character(k) <- data.frame(get(paste(i,as.character(k),sep="")))
    }
}

But this doesn't work. Is this because I should write "paste()" around some of this code, or is this simply a bad way to approach this problem? What is the correct way to loop through i and k and get a "newdata" dataframe as the final result with all the vectors as columns attached?

解决方案

Are you trying to achieve something like the following, perhaps?

name1 <- letters[1:10]
age1 <- 1:10
name20 <- letters[11:20]
age20 <- 11:20
name38 <- LETTERS[1:10]
age38 <- 21:30

paste.pattern <- paste(rep(c("name", "age"), times = 3), 
                       rep(c(1, 20, 38), each = 2), sep = "")

newdata <- data.frame(sapply(paste.pattern, get))

这篇关于在R中,如何轻松地将多个向量组合成数据帧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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