2017-08-09 43 views
0

我創建了一個數據框,其中列A和B包含子列。這裏有一個例子:如何去卷積2D數據幀?

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

使用'dput'做重複的例子 – Sotos

回答

0

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

首先讓我們創建一些示例數據。讓我知道這是不是你的數據看起來如何。

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") 
+0

遇到錯誤試圖UNNEST時: 錯誤:data_frames只能包含一維原子向量和列表 – user2904120

+0

請參閱我的數據幀結構的更新後的上述 – user2904120

+0

它看起來像你的數據已經在所需的格式。 –