Retain Vector Names as Dataframe Column Names

In my code, I am filling the columns of a dataframe with vectors, as so:

df1[columnNum] <- barWidth

This works fine, except for one thing: I want the name of the vector variable (barWidth above) to be retained as the column header, one column at a time. Furthermore, I do not wish to use cbind. This slows the execution of my code down considerably. Consequently, I am using a pre-allocated dataframe.

Can this be done in the vector-to-column assignment? If not, then how do I change it after the fact? I can't find the right syntax to do this with colNames().

TIA

Answers


If you have the list of names of vectors you want to apply you could do:

namevec <- c(...,"barWidth"...,)
columnNums <- c(...,10,...)

df1[columnNums[i]] <- get(namevec[i])
names(df1)[columnNums[i]] <- namevec[i]

or even

columnNums <- c(barWidth=4,...)
for (i in seq_along(columnNums)) {
   df1[columnNums[i]] <- get(names(columnNums)[i])
}
names(df1)[columnNums] <- names(columnNums)

but the deeper question would be where this set of vectors is coming from in the first place: could you have them in a list all along?


It's being done by the [<-.data.frame function. It could conceivably be replaced by one that looked at the name of the argument but it's such a fundamental function I would be hesitant. Furthermore there appears to be an aversion to that practice signaled by this code at the top of the function definition:

> `[<-.data.frame`
function (x, i, j, value) 
{
    if (!all(names(sys.call()) %in% c("", "value"))) 
        warning("named arguments are discouraged")
    nA <- nargs()
    if (nA == 4L) {
 <snipped rest of rather long definition>

I don't know why that is there, but it is. Maybe you should either be thinking about using names<- after the column assignment, or using this method:

> dfrm["barWidth"] <- barWidth

> dfrm
  a V2 barWidth
1 a  1        1
2 b  2        2
3 c  3        3
4 d  4        4

This can be generalized to a list of new columns:

dfrm <- data.frame(a=letters[1:4])
barWidth <- 1:4
newcols <- list(barWidth=barWidth, bw2 =barWidth)
dfrm[names(newcol)] <- newcol
dfrm
#
  a barWidth bw2
1 a        1   1
2 b        2   2
3 c        3   3
4 d        4   4

Need Your Help


About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.