16

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))
}

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.

in the end I would like to end up with

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 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
}

this however doesn't maintain column names

Dason
  • 60,663
  • 9
  • 131
  • 148
mmann1123
  • 5,031
  • 7
  • 41
  • 49

3 Answers3

23

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)
}

which gives

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

Alternatively, paste("Name", i, sep="") could be replaced with paste0("Name", i)

Brian Diggs
  • 57,757
  • 13
  • 166
  • 188
3

Maybe you want this:

R> A <- data.frame(a=c(1,2,3), b=c(3,6,2))
R> colnames(A) <- paste("Names", 1:ncol(A), sep="")
R> A
  Names1 Names2
1      1      3
2      2      6
3      3      2
R> 

but as Tyler said in the comment, it is not entirely clear what you are asking.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • Thanks for responding I just clarified what I was looking for. – mmann1123 May 16 '12 at 18:17
  • Just assign four columns at the beginning, and then the names when/where/how you want them. My answer already shows you `colnames(A)`, you can also just assign to `colnames(A)[3:4]` or any other valid expression. – Dirk Eddelbuettel May 16 '12 at 18:23
3

Still not entirely sure what you're trying to accomplish:

A = data.frame(a = c(1,2,3), b=c(3,6,2))
B <- data.frame(A, c(6, 3, 2), c(6, 3, 2))
names(B)[3:4] <- paste0("name", 1:2)
B

Which yields:

  a b name1 name2
1 1 3     6     6
2 2 6     3     3
3 3 2     2     2
Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519