stats_noob
stats_noob

Reputation: 5897

R: Make Each Element of a List into a Column

I am using the R programming language.

I have the following input ("input"):

> input
$coords
        x         y 
-85.70288  35.41780 

> str(input)
List of 1
 $ coords: Named num [1:2] -85.70288 35.41780
  ..- attr(*, "names")= chr [1:2] "x" "y"

> dput(input)
list(coords = c(x = -85.70288, y = 35.41780))

I would like to convert this into a data frame with two columns. For example:

> input
          x       y
1 -85.70288 35.4178

I tried the following code - but this did not work:

df <- data.frame(matrix(unlist(input), nrow=length(input), byrow=TRUE))

Does anyone know how to do this?

Thanks!

Upvotes: 1

Views: 644

Answers (2)

SAL
SAL

Reputation: 2140

df <- data.frame(t(input[["coords"]]))

Upvotes: 1

Joris C.
Joris C.

Reputation: 6234

First convert the coords vector to a list, after which it can be passed to e.g. data.frame() or as.data.frame():

data.frame(as.list(input$coords))
#>           x       y
#> 1 -85.70288 35.4178

as.data.frame(as.list(input$coords))
#>           x       y
#> 1 -85.70288 35.4178

Or similarly, to create a tibble:

dplyr::as_tibble(as.list(input$coords))
#> # A tibble: 1 × 2
#>       x     y
#>   <dbl> <dbl>
#> 1 -85.7  35.4

Or a data.table:

data.table::as.data.table(as.list(input$coords))
#>            x       y
#> 1: -85.70288 35.4178

Upvotes: 1

Related Questions