2014-09-21 35 views
31

tidyr的文檔表明收集和傳播是傳遞性的,但以下帶有「虹膜」數據的示例顯示它們不是,但不清楚原因。任何澄清,將不勝感激傳播帶有重複標識符的data.frame/tibble

iris.df = as.data.frame(iris) 
long.iris.df = iris.df %>% gather(key = feature.measure, value = size, -Species) 
w.iris.df = long.iris.df %>% spread(key = feature.measure, value = size, -Species) 

我期望的數據幀「w.iris.df」是相同的爲「iris.df」,但收到以下錯誤,而不是:

"Error: Duplicate identifiers for rows (1, 2, 3, 4, 5, 6, 7, 8, 9..."

我一般問題是如何在這類數據集上反轉「聚集」的應用。

+29

這不是傳遞性的,因爲沒有足夠的變量來唯一標識觀察值。嘗試添加像'iris.df $ row < - 1:nrow(iris.df)' – hadley 2014-09-23 03:06:09

+0

非常感謝!完美糾正我的誤解。 – 2014-09-23 22:30:47

回答

23

哈德利的干預措施毫不令人吃驚地完美無瑕...但在此之後,我最終得到了一些語法錯誤...所以爲了它的價值,我發佈了完全可操作的代碼(對不起,我的語法與上面有點不同) :

library(tidyr) 
library(dplyr) 

wide <- 
    iris %>% 
    mutate(row = row_number()) %>% 
    gather(vars, val, -Species, -row) %>% 
    spread(vars, val) 

head(wide) 
# Species row Petal.Length Petal.Width Sepal.Length Sepal.Width 
# 1 setosa 1   1.4   0.2   5.1   3.5 
# 2 setosa 2   1.4   0.2   4.9   3.0 
# 3 setosa 3   1.3   0.2   4.7   3.2 
# 4 setosa 4   1.5   0.2   4.6   3.1 
# 5 setosa 5   1.4   0.2   5.0   3.6 
# 6 setosa 6   1.7   0.4   5.4   3.9 

head(iris) 
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species 
# 1   5.1   3.5   1.4   0.2 setosa 
# 2   4.9   3.0   1.4   0.2 setosa 
# 3   4.7   3.2   1.3   0.2 setosa 
# 4   4.6   3.1   1.5   0.2 setosa 
# 5   5.0   3.6   1.4   0.2 setosa 
# 6   5.4   3.9   1.7   0.4 setosa 

他們是一樣的....只需如果u喜歡它重新安排......

wide <- wide[,c(3, 4, 5, 6, 1)] ## Reorder and then remove "row" column 

和完成。