38

tidyr 的文档表明收集和传播是可传递的,但以下带有“iris”数据的示例显示它们不是,但不清楚原因。任何澄清将不胜感激

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”相同,但收到以下错误:

“错误:行标识符重复(1、2、3、4、5、6、7、8、9...”

我的一般问题是如何在这种数据集上反转“收集”的应用。

4

2 回答 2

29

哈德利的干预出人意料地完美......但在那之后我最终对语法做了一些修改......所以为了它的价值,我发布了完全可操作的代码(抱歉我的语法与上面有点不同):

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

它们是相同的......如果你喜欢它只需要重新排序......

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

并做了。

于 2014-11-19T11:56:12.533 回答
0

由于先前的答案可能不够清楚,因此gather当您尝试执行时,您的执行方式存在问题spread

问题是,在收集过程中,您无法跟踪feature.measure原始数据框中的哪一行,因此spread不知道如何将各个值再次组合到“宽”表中。

iris.df = as.data.frame(iris)
long.iris.df = iris.df %>% 
  tibble::rowid_to_column() %>% 
  gather(key = feature.measure, value = size, -Species, -rowid)

#>   rowid Species feature.measure size
#> 1     1  setosa    Sepal.Length  5.1
#> 2     2  setosa    Sepal.Length  4.9
#> 3     3  setosa    Sepal.Length  4.7
#> 4     4  setosa    Sepal.Length  4.6
#> 5     5  setosa    Sepal.Length  5.0
#> 6     6  setosa    Sepal.Length  5.4

现在每个值都size保留了它rowid,因此您将始终能够将其重新组合回宽数据集(删除不必要的rowid):

w.iris.df = long.iris.df %>% 
  spread(key = feature.measure, value = size) %>% 
  select(-rowid)
head(w.iris.df)
#>   Species Petal.Length Petal.Width Sepal.Length Sepal.Width
#> 1  setosa          1.4         0.2          5.1         3.5
#> 2  setosa          1.4         0.2          4.9         3.0
#> 3  setosa          1.3         0.2          4.7         3.2
#> 4  setosa          1.5         0.2          4.6         3.1
#> 5  setosa          1.4         0.2          5.0         3.6
#> 6  setosa          1.7         0.4          5.4         3.9
于 2018-11-13T14:10:29.713 回答