Home > front end >  R: Make Each Element of a List into a Column
R: Make Each Element of a List into a Column

Time:10-18

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!

CodePudding user response:

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

CodePudding user response:

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
  • Related