Reputation: 137
When trying to convert data frame to a list resembling a nested dictionary I tried using a following command:
df = data.frame(col1 = c('a', 'b'), col2 = c(1, 2))
df[,1] = as.character(df[,1])
ls1 = apply(df, 1, as.list)
print(ls1)
However, the values of col2 in ls1 now seem to be converted to character:
class(ls1[[2]]$col2)
# [1] "character"
This workaround works, but I am curious if somebody knows, why the result is not the same as in previous code?
ls2 = as.list(df[1,])
for(i in 2:nrow(df)){
ls2 = list(ls2, as.list(df[i,]))
}
print(ls2)
class(ls1[[2]]$col2)
# [1] "numeric"
Upvotes: 1
Views: 130
Reputation: 887511
Instead of apply
, which converts the data to matrix
and matrix
can have only single class, use split
lst1 <- unname(split(df, seq_len(nrow(df))))
If we need a JSON
output, the dataset can be directly converted to JSON
with toJSON
jsonlite::toJSON(df)
#[{"col1":"a","col2":1},{"col1":"b","col2":2}]
Based on the conversation with OP, dataset is passed as a named list
that needs to be converted to JSON format
toJSON(list(listName = df))
#{"listName":[{"col1":"a","col2":1},{"col1":"b","col2":2}]}
Upvotes: 2