如何解卷积2D数据框?

时间:2017-08-09 11:07:47

标签: r dataframe

我创建了一个数据框,其中A列和B列包含子列。这是一个例子:

colnames(df) 
#[1] "A" "B" "C" "D"

colnames(df$A)
#[1] "X1" "X2" "X3" "X4"

colnames(df$B)
#[1] "X1" "X2"

我的问题是如何将这种结构解卷积为:

colnames(df)
#[1] "A.X1" "A.X2" "A.X3" "A.X4" "B.X1" "B.X2"

示例:

structure(list(Name = 1:5, A = structure(list(X1 = structure(c(1L, 
2L, 1L, 2L, 1L), .Label = c("1", "5"), class = "factor"), X2 = structure(c(1L, 
2L, 1L, 2L, 1L), .Label = c("2", "4"), class = "factor"), X3 = structure(c(2L, 
1L, 2L, 1L, 2L), .Label = c("3", "4"), class = "factor"), X4 = structure(c(2L, 
1L, 2L, 1L, 2L), .Label = c("1", "5"), class = "factor")), .Names = c("X1", 
"X2", "X3", "X4"), row.names = c(NA, -5L), class = "data.frame"), 
    B = structure(list(X1 = structure(c(2L, 1L, 2L, 1L, 2L), .Label = c("1", 
    "5"), class = "factor"), X2 = structure(c(2L, 1L, 2L, 1L, 
    2L), .Label = c("2", "4"), class = "factor")), .Names = c("X1", 
    "X2"), row.names = c(NA, -5L), class = "data.frame")), .Names = c("Name", 
"A", "B"), row.names = c(NA, -5L), class = "data.frame")

1 个答案:

答案 0 :(得分:0)

您可以使用unnest()包中的tidyr功能。

首先让我们创建一些示例数据。如果这不是您的数据外观,请告诉我。

library(tidyverse) # Loads tidyr, tibble, and other useful packages

df <- tibble(A = list(tibble(X1 = rnorm(327), X2 = rnorm(327),
             X3 = rnorm(327), X4 = rnorm(327))),
             B = list(tibble(X1 = rnorm(327), X2 = rnorm(327))))

现在unnest,你差不多完成了。

df <- unnest(df)

剩下的就是重命名列,因为unnest会自动显示自己的名称。

colnames(df) <- c("A.X1", "A.X2", "A.X3", "A.X4", "B.X1", "B.X2")