0

I have a simple data.frame df

a    b    c     d
1    5    A     E
2    4    B     F
3    3    C     G
4    2    D     H
5    1    E     J

Let's say I want to write it in JSON format:

jsonlite::toJSON(df[1,])

returns:

[{"a":1,"b":10,"c":"A","d":"J"}]

However,

apply(df[1,], 1, jsonlite::toJSON)

returns:

"[\"1\",\"10\",\"A\",\"J\"]"

Where did the names of my variables go? How can I get them back?

Thanks,

Carlos

Carlos
  • 371
  • 5
  • 16

1 Answers1

0

help(apply) tells you:

 If ‘X’ is not an array but an object of a class with a non-null
 ‘dim’ value (such as a data frame), ‘apply’ attempts to coerce it
 to an array via ‘as.matrix’ if it is two-dimensional (e.g., a data
 frame) or via ‘as.array’.

so toJSON sees a character vector for each row of what was a data frame.

Solution is to split the data frame and use lapply:

> lapply(split(df, 1:nrow(df)), jsonlite::toJSON)
$`1`
[{"a":1,"b":5,"c":"A","d":"E"}] 
$`2`
[{"a":2,"b":4,"c":"B","d":"F"}] 
$`3`
[{"a":3,"b":3,"c":"C","d":"G"}] 
$`4`
[{"a":4,"b":2,"c":"D","d":"H"}] 
$`5`
[{"a":5,"b":1,"c":"E","d":"I"}] 
Spacedman
  • 92,590
  • 12
  • 140
  • 224