将数据帧中的字符串拆分为R中的json数组 [英] Split string in dataframe to json array in R
本文介绍了将数据帧中的字符串拆分为R中的json数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要从R中的 dataframe 导出json(使用jsonlite).一切正常,除了一件事.我在像这样的单元格中有带有字符串的列:
I need to export json from dataframe in R (use jsonlite). Everything's OK, except one thing. I have column with string in cells like this:
"one,two,three"
之后:
sink("out.json")
cat(toJSON(DF, pretty = TRUE))
sink()
Json看上去:
{..."data" : "one,two,three"...}
我想要数组:
{..."data" : ["one","two","three"]...}
我试图用strsplit覆盖单元格并用json替换单元格的值,但是它不起作用.
I tried strsplit to overwrite cell and replace value of cell with json, but it's not working.
strsplit:
==================
Warning message:
In `[<-.data.frame`(`*tmp*`, 16, 5, value = list(c("one", :
replacement element 1 has 3 rows to replace 1 rows
strplit and toJSON for cell:
==================
[1] "[\"one\",\"two\",\"three\"]"
有人可以帮助我吗?谢谢!
Can someone help me? Thanks!
推荐答案
您可以将列更改为列表,而不是字符向量.
You can mutate the column to be a list rather than a character vector.
library('jsonlite')
library('tidyverse')
df <- tribble(
~column1, ~data,
1, 'one,two,three',
2, 'four,five'
)
df <- df %>%
mutate(data = stringr::str_split(data, ','))
toJSON(df, pretty = T)
# [
# {
# "a": 1,
# "data": ["one", "two", "three"]
# },
# {
# "a": 2,
# "data": ["four", "five"]
# }
# ]
这篇关于将数据帧中的字符串拆分为R中的json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文