从特定的 R 数据框列添加 JSON 列

Adding a JSON column from specific R dataframe columns

我有一个 R 数据框,其中包含我想附加到 JSON 列中的特定列

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))

我想要 df 数据框中的 JSON 项目维度列,每个维度在单个项目维度列中由“x”分隔。

   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"}

我尝试使用 jsonlite 包,但没有得到我想要的结果。我也在 dplyr 包中工作,所以 dpylr::mutate 解决方案将不胜感激。

克里斯 - 欢迎来到 SO!这是使用 dplyr 的尝试。您首先要使用 rowwiseauto_unbox 选项将删除额外的括号以匹配您想要的输出。

library(tidyverse)
library(jsonlite)

df %>%
  rowwise %>%
  mutate(item_dimensions = toJSON(list(size = paste(Length, Width, Height, sep = " x ")), auto_unbox = T))

输出

  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"}