在 R 中使用字符串名称分配 data.frame 的列 [英] Assign a column of a data.frame with string name in R

查看:25
本文介绍了在 R 中使用字符串名称分配 data.frame 的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据分配给现有数据框,并在循环中生成名称.一个基本的例子可能是

I am trying to assign data to an existing dataframe with a name generated in a loop. A basic example might be

A = data.frame(a = c(1,2,3), b=c(3,6,2))

for (i in 1:2){
    name = paste("Name",i, sep="")
    assign(name, c(6,3,2))
}

现在我只需要弄清楚如何将 name1 和 name2 添加到 data.frame A,同时保留它们指定的名称.我相信有一个简单的答案,只是我现在没有看到.

Now I just need to figure out how to add name1 and name2 to the data.frame A, while keeping their assigned name. I'm sure there is an easy answer, I'm just not seeing it right now.

最后我想结束

A
#a b name1 name2
#1 3 6      6
#2 6 3      3
#3 2 2      2

但我需要以自动方式执行此操作.

But I need to do this in an automated fashion.

例如,如果 for 循环可以像

For instance if the for loop could be adapted to be like

for (i in 1:2){
    name = paste("Name",i, sep="")
    assign(name, c(6,3,2)
    A= cbind(A, get(paste(name,i,sep="")))  # works but doesn't maintain the column name as name1 or name2 etc
}

然而这不维护列名

推荐答案

其他答案都很好,但是如果您像以前一样使用循环,那么这将起作用:

The other answers are good, but if you are set on using a loop like you have, then this would work:

A <- data.frame(a = c(1,2,3), b = c(3,6,2))

for (i in 1:2){
    A[paste("Name", i, sep="")] <- c(6,3,2)
}

给出

> A
  a b Name1 Name2
1 1 3     6     6
2 2 6     3     3
3 3 2     2     2

或者,paste("Name", i, sep="") 可以替换为 paste0("Name", i)

这篇关于在 R 中使用字符串名称分配 data.frame 的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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