【问题标题】:How do I split or create a new column for a list of data in a dataframe?如何为数据框中的数据列表拆分或创建新列?
【发布时间】:2019-01-13 15:11:58
【问题描述】:

请看一下图片中数据的预览。我想创建 3 个新列,即开始、结束、密度,并为这 3 个列中的每条记录创建新行。

【问题讨论】:

  • 请阅读有关how to ask a good question 的信息以及如何提供reproducible example。这将使其他人更容易帮助您。
  • data.frame(start = c(...), end = c(...), density = c(...)?
  • as.data.frame(data1[["first_paint.histogram.bin"]][1])?
  • 在您的列表中,开始、结束和密度的长度是否匹配?如果是这样,就做data.frame(mylist)
  • 另外,请不要将数据或代码作为图像发布。为什么?请阅读Why not upload images of code?

标签: r data-cleaning data-munging


【解决方案1】:

根据上面的cmets,您可以将list转换为data.frame,如下所示:

# simulation of data.frame with one row and one cell with histogram
z <- hist(rnorm(1000))
z$start <- z$breaks[-length(z$breaks)]
z$end <- z$breaks[-1]
z[c("mids", "xname", "breaks", "equidist", "counts")] <- NULL
names_z <- names(z)
attributes(z) <- NULL
df <- data.frame(a = 1, b = 2, x = I(list((z))))

# Conversion of list to dataframe
setNames(as.data.frame(unlist(df["x"], recursive = FALSE)), names_z)

输出:

   density start  end
1    0.012  -3.0 -2.5
2    0.042  -2.5 -2.0
3    0.082  -2.0 -1.5
4    0.182  -1.5 -1.0
5    0.288  -1.0 -0.5
6    0.354  -0.5  0.0
7    0.418   0.0  0.5
8    0.300   0.5  1.0
9    0.172   1.0  1.5
10   0.088   1.5  2.0
11   0.050   2.0  2.5
12   0.012   2.5  3.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 2022-12-22
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多