Skip to main content
  1. About
  2. For Teams
Asked
Modified 7 years ago
Viewed 41 times
Part of R Language Collective
0

If I have a list with two columns (name and its corresponding value), how do I convert it into a data frame with the two labels?

Desired output:

NAME   NUMBER
Andy   50534

Angela 15857

Creed   5004

Darryl  12246

I don't know why when I used as.data.frame(df), it gave me a horizontal data frame like this:

Andy Angela Creed Darryl
50534 15857 5004  12246
1
  • and how does your list look?
    Ronak Shah
    –  Ronak Shah
    2018-10-12 02:16:13 +00:00
    Commented Oct 12, 2018 at 2:16

2 Answers 2

1

One approach uses cbind to convert the list into a data frame:

lst <- list(NAME=c("Andy", "Angela", "Creed", "Darryl"),
            NUMBER=c(50534, 15857, 5004, 12246))
data.frame(do.call("cbind",lst))

    NAME NUMBER
1   Andy  50534
2 Angela  15857
3  Creed   5004
4 Darryl  12246

Demo

Sign up to request clarification or add additional context in comments.

Comments

0

Preparation

lst <- list(NAME=c("Andy", "Angela", "Creed", "Darryl"),
            NUMBER=c(50534, 15857, 5004, 12246))

Simplest solution

df <- as.data.frame(lst, stringsAsFactors=FALSE)

Uses the fact that a data frame is in its core a list of column vectors. So, a simple as.data.frame call on the list will do automatically many things just right. I always apply stringsAsFactors=FALSE when creating a data frame, since I don't want a column with strings becomes a factor column like it is default in base R.

Result

df
##     NAME NUMBER
## 1   Andy  50534
## 2 Angela  15857
## 3  Creed   5004
## 4 Darryl  12246

Comments

Your Answer

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.