[R] Assigning variable value as name to cbind column

Bill.Venables at csiro.au Bill.Venables at csiro.au
Fri Jun 25 08:43:37 CEST 2010

Why does the naming have to be done inside the cbind()?

How about

> dataTest <- data.frame(col1 = c(1,2,3))
> new.data <- c(1,2)
> name <- "test"

> length(new.data) <- nrow(dataTest)
> newDataTest <- cbind(dataTest, new.data)
> names(newDataTest)[[ncol(newDataTest)]] <- name
> newDataTest
  col1 test
1    1    1
2    2    2
3    3   NA


-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Ralf B
Sent: Friday, 25 June 2010 3:48 PM
To: r-help at r-project.org
Subject: [R] Assigning variable value as name to cbind column

Hi all,

I have this (non-working) script:

dataTest <- data.frame(col1=c(1,2,3))
new.data <- c(1,2)
name <- "test"
n.row <- dim(dataTest)[1]
length(new.data) <- n.row
names(new.data) <- name
cbind(dataTest, name=new.data)

and would like to bind the new column 'new.data' to 'dataTest' by
using the value of the variable 'name' as the column name.

The end result should look like this:

      col1     test
1      1          1
2      2          2
3      3          NA

The best I got was that 'name' became the column name but never the
actual value of 'name'. How can i do that?

(This is actually a function that runs many time -- this means a
manual workaround is not feasible).


R-help at r-project.org mailing list
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list