tags:

views:

207

answers:

3

I have a list called cols with column names in it:

cols <- c('Column1','Column2','Column3')

I'd like to reproduce this command, but with a call to the list:

data.frame(Column1=rnorm(10))

Here's what happens when I try it:

> data.frame(cols[1]=rnorm(10))

Error: unexpected '=' in "data.frame(I(cols[1])="

The same thing happens if I wrap cols[1] in I() or eval().

How can I feed that item from the vector into the data.frame() command?

Update:

For some background, I have defined a function calc.means() that takes a data frame and a list of variables and performs a large and complicated ddply operation, summarizing at the level specified by the variables.

What I'm trying to do with the data.frame() command is walk back up the aggregation levels to the very top, re-running calc.means() at each step and using rbind() to glue the results onto one another. I need to add dummy columns with 'All' values in order to get the rbind to work properly.

I'm rolling cast-like margin functionality into ddply, basically, and I'd like to not retype the column names for each run. Here's the full code:

cols <- c('Col1','Col2','Col3')
rbind ( calc.means(dat,cols),
    data.frame(cols[1]='All', calc.means(dat, cols[2:3])),
    data.frame(cols[1]='All', cols[2]='All', calc.means(dat, cols[3]))
)
+1  A: 

I'm not sure how to do it directly, but you could simply skip the step of assigning names in the data.frame() command. Assuming you store the result of data.frame() in a variable named foo, you can simply do:

names(foo) <- cols

after the data frame is created

frankc
Yes, this would normally work, but the `data.frame()` happens inside an `rbind()`. Thanks, though.
MW Frost
You could create the data frame, assign the column names, and then rbind them, all in one clause.
Shane
Shane,How would that work? I'm not sure how to pass the objects through the process in a single clause.
MW Frost
+1  A: 

Use can use structure:

cols <- c("a","b")

foo <- structure(list(c(1, 2 ), c(3, 3)), .Names = cols, row.names = c(NA, -2L), class = "data.frame")

I don't get why you are doing this though!

Eduardo Leoni
+1  A: 

There is one trick. You could mess with lists:

cols_dummy <- setNames(rep(list("All"), 3), cols)

Then if you use call to list with one paren then you should get what you want

data.frame(cols_dummy[1], calc.means(dat, cols[2:3]))

You could use it on-the-fly as setNames(list("All"), cols[1]) but I think it's less elegant.

Example:

some_names <- list(name_A="Dummy 1", name_B="Dummy 2") # equivalent of cols_dummy from above
data.frame(var1=rnorm(3), some_names[1])
#        var1  name_A
# 1 -1.940169 Dummy 1
# 2 -0.787107 Dummy 1
# 3 -0.235160 Dummy 1
Marek