Gopala
Gopala

Reputation: 10483

Convert each data frame row to httr body parameter list without enumeration

So, I have a data frame that carries a bunch of values for two form fields. I want to make POST requests per row as follows:

df <- data.frame(x = 1:5, y = 1:5)
apply(df, 1, function(x) {
       POST(someURL, accept_json(),
            add_headers('Content-Type' = 'application/json'),
            body = list('x' = x[1], 'y' = x[2]), encode = 'json'))
       })

This works fine. However, is there a way to generate list('x' = x[1], 'y' = x[2]) programmatically without enumerating each value like that since the names of the columns in the data frame are basically the list.

Upvotes: 2

Views: 235

Answers (1)

HubertL
HubertL

Reputation: 19544

You can iterate on indices, and use as.list():

df <- data.frame(x = 1:5, y = 1:5)
lapply(seq_along(df[,1]), function(x) {
       POST(someURL, accept_json(),
            add_headers('Content-Type' = 'application/json'),
            body = as.list(df[x,]), encode = 'json')
})

Upvotes: 1

Related Questions