Olivier
Olivier

Reputation: 11

How to create a data.frame with a unknown number of columns?

I would like to create, in a function, a loop 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 tried with rbind, but it doesn't work...

Upvotes: 1

Views: 5713

Answers (4)

Shane
Shane

Reputation: 100164

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

Upvotes: 6

Olivier
Olivier

Reputation: 11

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.

Upvotes: 0

Brani
Brani

Reputation: 6784

Another way

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

library(plyr)
df <- ldply(b)
rownames(df) <- a

Upvotes: 2

James
James

Reputation: 66834

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

Upvotes: 3

Related Questions