我们可以用data.table
to paste
“年份”和“销售额”列按“组”分组。我们将“data.frame”转换为“data.table”(setDT(df1)
)。按“组”分组,我们使用sprintf
将“年份”、“销售额”与括号一起粘贴([]
),然后将输出折叠为单个字符串toString
(它是一个包装器paste(..., collapse=', ')
), paste
the []
,并使用toJSON
.
library(jsonlite)
library(data.table)
toJSON(setDT(df1)[, list(sales= paste0('[',toString(sprintf('[%d,%d]',
year, sales)),']')), by = group])
#[{"group":1,"sales":"[[2000,20], [2001,25], [2002,23], [2003,30]]"},
#{"group":2,"sales":"[[2001,50], [2002,55]]"}]
The paste
按组可以使用base R
. We split
数据集按“组”列创建list
。循环遍历list
with lapply
, paste
、“年份”、“销售额”栏如上所述。创建一个data.frame
与 'group' 的第一个元素和来自paste
step, rbind
the list
元素来创建单个data.frame
然后使用toJSON
.
toJSON(
do.call(rbind,
lapply(
split(df1, df1$group),
function(x) data.frame(group=x$group[1L],
sales=paste0('[',
toString(sprintf('[%d,%d]', x$year, x$sales)),
']')))))
data
df1 <- structure(list(year = c(2000L, 2001L, 2002L, 2003L, 2001L, 2002L
), group = c(1L, 1L, 1L, 1L, 2L, 2L), sales = c(20L, 25L, 23L,
30L, 50L, 55L)), .Names = c("year", "group", "sales"),
class = "data.frame", row.names = c(NA, -6L))