2016-03-01 99 views
0

我在R中的數據幀形式的數據集如下拆分列表和

col 1 col 2     col3       col 4 
941  3605     c(0.035,0.298)     20/08/2013 00:00:00 
929  3575     c(0.026,0.078,0.292)   20/08/2013 00:00:00 

我想在第3列分裂列表,並將其添加到主數據幀導致以下內容

col 1 col 2  col3    col 4 
941  3605   0.035   20/08/2013 00:00:00 
941  3605   0.298   20/08/2013 00:00:00 
929  3575   0.026   20/08/2013 00:00:00 
929  3575   0.078   20/08/2013 00:00:00 
929  3575   0.0292   20/08/2013 00:00:00 

有人可以幫忙嗎?

+0

退房'splitstackshape :: listCol_l' –

+0

丹娜絲您好,我曾試圖用http://stackoverflow.com/questions/在這篇文章中描述的過程15930880/unlist-all-list-elements-in-a-dataframe 它將數據集分割爲列,我無法弄清楚如何重新調整它以達到我想要的結果。 – theArun

+0

@DavidArenburg,謝謝!這正是我一直在尋找的!乾杯! – theArun

回答

0

下面是一個使用@ DavidArenburg解決新COL3建議的包{splitstackshape}和包{dplyr}來整理轉換:

```

df <- data.frame(col_1 = c(941, 929), 
       col_2 = c(3605,3575), 
       col_3 = I(list(c(0.035, 0.298),c(0.026, 0.078, 0.292))), 
       col_4 = c("0/08/2013 00:00:00", "20/08/2013 00:00:00")) 

res <- splitstackshape::listCol_l(df, listcol = "col_3", drop = TRUE) 


res <- dplyr::select(res, col_1, col_2, col_3_ul, col_4) 
names(res)[3] <- "col_3" 
print(res) 

## col_1 col_2 col_3    col_4 
##1: 941 3605 0.035 0/08/2013 00:00:00 
##2: 941 3605 0.298 0/08/2013 00:00:00 
##3: 929 3575 0.026 20/08/2013 00:00:00 
##4: 929 3575 0.078 20/08/2013 00:00:00 
##5: 929 3575 0.292 20/08/2013 00:00:00 

```

0

像這樣的東西可以幫助你

我明白COL3是一個列表......如果不是第一次這樣做:

yourdata$col3 <- strsplit (yourdata$col3, ",") 

然後找到每個元素的長度COL3

l <- sapply (yourdata$col3, length) 

和行數

N <- nrow (yourdata) 

爲您的新的數據集

my.new.rows <- rep (1:N, times = l) 

創建一個 「指數」 創建新的數據集

yornewdata <- yourdata[my.new.rows,] 

並添加

yornewdata[,"new3"] <- unlist (yourdata$col3)