Turn Dataframe Row into a List

I have an API call that works when the string is created as a list. If instead take a row of a data frame it wrapsit in brackets [
] and fails.

I'm looking to create a list from the row of the data frame to get it to work again.

For example.

If I create a list using

Fields<-list("Sex"="M","Age"=10)

and then put that into a list:

body<-list("ID"="E1","Inputs"=Fields)

the body works fine

however if I have a dataframe, df
Sex Age
M 10
F 20

and i use:

body<-list("ID"="E1",df[1,])

It creates body as a list of 3, but the 3rd element itself is a data.frame with 1 row and 2 columns rather than a list.

How can I convert the single data frame row to a list?

Thanks!

Okay, I've figured out a workaround, instead of : body<-list("ID"="E1",df[1,])

I can use: body<-list("ID"="E1",unbox(df[1,]))

Seems to do the trick.

Hi there, looks like you're running into how R subsets lists. Using [ to subset a data frame (which is actually a list of vectors) returns another list. If you want to return a vector from a list, you could use either [[ or $. Below are examples of what I think you're aiming for:

df <- tibble::tribble(
  ~Sex, ~Age,
  "M", 10,
  "F", 20
  )

list("ID" = "E1", df$Sex)
#> $ID
#> [1] "E1"
#> 
#> [[2]]
#> [1] "M" "F"
list("ID" = "E1", df[[1, ]])
#> $ID
#> [1] "E1"
#> 
#> [[2]]
#> [1] "M" "F"

Created on 2019-01-25 by the reprex package (v0.2.1)

There is lots more details about subsetting lists, including a great train car metaphor here:

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.