tags:

views:

214

answers:

4

Hello I would like to create, in a function, a boucle to create a data.frame with a variable number of columns.

WIth something like :

a = c("a","b")
b = c(list(1,2,3), list(4,5,6))
data.frame(a,b)

I would like to get a data-frame like :

a 1 2 3
b 4 5 6

Instead of I obtain :

a  1  2  3  4  5  6
b  1  2  3  4  5  6

Thank you !

PS : I also try with rbind, but it's doesn't work...

+2  A: 

Do you have the 2 lists in b held as separate variables?

If so you can use:

x<-data.frame(rbind(b1,b2))
rownames(x)<-a
James
+5  A: 

There are many ways to do this kind of thing. Your first problem is that your "b" object is not a matrix. You need to define it as one with rows and columns (or by using rbind).

You can create the data frames and then combine them (this is better than working with a matrix to begin with, because it will maintain each objects type as numeric or character, etc., while a matrix would lose that):

x1 <- data.frame(X=c("a","b"))
x2 <- data.frame(rbind(c(1,2,3), c(4,5,6)))
data.frame(x1, x2)
  X X1 X2 X3
1  a  1  2  3
2  b  4  5  6

If x1 is for rownames, then you should follow James's example:

x2 <- data.frame(rbind(c(1,2,3), c(4,5,6)))
rownames(x2) <- c("a","b")
Shane
A: 

Another way

a = c("a","b")
b = list(c(1,2,3), c(4,5,6))

library(plyr)
df <- ldply(b)
rownames(df) <- a
Brani
A: 

Thank you a lot ! Before reading your response, I tried another method using :

for (x in niveaux) {
    assign(x,pi)
    assign(paste(x,"moy"),"moy")
    }
# Que j'utilise ensuite avec qq chose du genre :
assign(x,append(get(x),1))

But it's more complicated!

Olivier

PS : 'a' can be a rowname or a column, the aim is to export data.frame as a CSV file.

Olivier