marc_aragones marc_aragones - 15 days ago 8
JSON Question

Convert list to string of all dataframe rows

I hace the following dataframe:

json = '[
{"id":"1","list":["A","B"]},
{"id":"2","list":["C","D"]}
]'
df <- fromJSON(json)
df


Output:

id list
1 1 c("A", "B")
2 2 c("C", "D")


Now, I want the list to be a string like this:

id list
1 1 "A, B"
2 2 "C, D"


So, I've tried the following but nothing changes:

df$list <- paste(df$list, sep = ", ")


I've also tried the following but it concats the two lists in every row:

df$list <- toString(df$list)

# Output
id list
1 1 c("A", "B"), c("C", "D")
2 2 c("A", "B"), c("C", "D")


Is there a way to change every row separately?

Another solution would be to import the JSON arrays directly to a given format, is this possible?

Thanks!

Answer

We need to loop through the column and do the toString

df$list <- sapply(df$list, toString)