首页 > 解决方案 > 将一组值放入数据框中的单元格中

问题描述

更新:我重新措辞并重新思考了这个问题,我认为这个问题最好这样问。

所以我一直在破解这个,没有运气。这是我想要做的一个例子。

我从一个数据框开始:

df = data.frame("one" = c(1,11), "two" = c(2,22), "three" = c(3,33))

one  two  three
1    2    3
11   22   33

我正在尝试将上述内容变为:

one  new
1    c(2,3)
11    c(22,33)

我已经尝试了一些事情,比如嵌套 2 列并尝试映射它们等。也许有一些简单的东西我在这里看不到。我最好希望通过 tidyverse 在 R 中执行此操作,但此时我对任何事情都持开放态度。

必须这样,因为当它转换为 JSON 时,“新”下的值需要采用 [1,2,3] 和 [11,22,33] 的形式。也许在 Python 中更容易?

我正在使用 R 中的jsonlite包与 JSON 进行转换。

谢谢您的帮助。

标签: pythonrjsondata-manipulation

解决方案


I think this should just be a Map exercise:

df$new <- Map(c, df$two, df$three)
df
#  one two three    new
#1   1   2     3   2, 3
#2  11  22    33 22, 33

library(jsonlite)
toJSON(df[c("one","new")])
#[{"one":1,"new":[2,3]},{"one":11,"new":[22,33]}]

If you've got many variables, you can wrap it in do.call to get it done too:

df$new <- do.call(Map, c(c,df[2:3]))

If tidyverse is your preference, you can purrr it like:

map2(df$two, df$three, c)

推荐阅读