如何为数据框中的数据列表拆分或创建新列?

时间:2018-08-06 15:46:01

标签: r data-cleaning data-munging

enter image description here

请查看图像中数据的预览。我想创建3个新列,即“开始”,“结束”,“密度”,并为这3列中的每个记录创建新行。

1 个答案:

答案 0 :(得分:0)

按照上面的评论,您可以将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