R 将列转换为 JSON rowwise

R convert columns to JSON rowwise

我有data.frame

df <- data.frame(a = c(1,3),b = c(2,4))

  a b
1 1 2
2 3 NA

我想收到这样的 data.frame:

  a  b           json
1 1  2 {"a":1, "b":2}
2 3 NA        {"a":3}

我想知道是否有一种方法可以通过

有效地得到这个结果
df <- df %>% dplyr::mutate(json = ?())

我自己没有粘贴值。在 Postgres 中有一个函数 json_strip_nulls(row_to_json(*)) 来获取它。 R 中是否有任何等效项?

你可以这样做:

library(jsonlite)
library(dplyr)

df <- data.frame(a = c(1,3),b = c(2,NA))

df %>%
  rowwise() %>%
  mutate(json = toJSON(across())) %>%
  ungroup()

# A tibble: 2 x 3
      a     b json           
  <dbl> <dbl> <json>         
1     1     2 [{"a":1,"b":2}]
2     3    NA [{"a":3}]  

stream_out 逐行使用 awesome jsonlite 包:

library(jsonlite)

df <- data.frame(a = c(1,3),b = c(2,NA))

tc <- textConnection("jsontxt", "w")
stream_out(df, con=tc)
df$json <- jsontxt
close(tc)

df
##  a  b          json
##1 1  2 {"a":1,"b":2}
##2 3 NA       {"a":3}

应该比在 R 中按行循环更有效:

df <- data.frame(a = c(1,3),b = c(2,NA))
df <- df[rep(1:2, 10000),]
rownames(df) <- NULL

system.time({
  tc <- textConnection("jsontxt", "w")
  stream_out(df, con=tc)
  df$json <- jsontxt
  close(tc)
})
##Complete! Processed total of 20000 rows.
##   user  system elapsed 
##   0.78    0.00    0.78 

library(dplyr)
system.time({
df %>%
  rowwise() %>%
  mutate(json = toJSON(across())) %>%
  ungroup()
})
##   user  system elapsed 
##  28.36    0.24   28.61