Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a list to one row data.frame

Tags:

list

dataframe

r

I have a list like this:

arg0 <- list(code = "a", n = rep(10, 3))

The number of objects in a list is variable. The objects of the list are vectors -- only one dimensional objects.

I want to make a procedure to convert the list to a one row data.frame like this:

> data.frame(code = "a", n.1 = 10, n.2 = 10, n.3 = 10)
  code n.1 n.2 n.3
1    a  10  10  10

I have this solution currently:

a <- stack(arg0)
b <- data.frame(t(a[,1]))
names(b) <- a[,2]
b <- data.frame(b)

Where b is almost the result I want to achieve:

> b
  code  n n.1 n.2
1    a 10  10  10

Two questions:

  1. Is there more elegant way to achieve the result?
  2. Do you have any idea how to get the numbering of the duplicate colnames like c(n.1, n.2, n.3)?
like image 563
djhurio Avatar asked Nov 26 '12 15:11

djhurio


1 Answers

This is one way:

data.frame(t(unlist(arg0)))
#   code n1 n2 n3
# 1    a 10 10 10
like image 171
Matthew Plourde Avatar answered Nov 15 '22 21:11

Matthew Plourde