I have an R dataframe with specific columns I want to append together into a JSON column
df = data.frame(item = c("Box 1", "Box 2", "Box 3"), Length = c(2, 4, 6), Width = c(4,5,3), Height = c(6, 4, 3))
I want a JSON item dimension column in the df data frame with each of the dimensions separated by an "x" in a single item dimensions column.
item Length Width Height item dimensions
1 Box 1 2 4 6 {"size":"2 x 4 x 6"}
2 Box 2 4 5 4 {"size":"4 x 5 x 4"}
3 Box 3 6 3 3 {"size":"6 x 3 x 3"}
I tried working with the jsonlite package but not getting the result I want. I am also working within the dplyr package too so a dpylr::mutate solution would be greatly appreciated.
CodePudding user response:
Chris - welcome to SO! This is something to try that uses dplyr. You will want to use rowwise first. The auto_unbox option will remove extra brackets to match your desired output.
library(tidyverse)
library(jsonlite)
df %>%
rowwise %>%
mutate(item_dimensions = toJSON(list(size = paste(Length, Width, Height, sep = " x ")), auto_unbox = T))
Output
item Length Width Height item_dimensions
<chr> <dbl> <dbl> <dbl> <json>
1 Box 1 2 4 6 {"size":"2 x 4 x 6"}
2 Box 2 4 5 4 {"size":"4 x 5 x 4"}
3 Box 3 6 3 3 {"size":"6 x 3 x 3"}
