tidyr的文档表明收集和传播是可传递的,但以下带有"虹膜"数据的示例显示它们不是,但不清楚为什么.任何澄清将不胜感激
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)
Run Code Online (Sandbox Code Playgroud)
我希望数据框"w.iris.df"与"iris.df"相同,但收到以下错误:
"错误:行的重复标识符(1,2,3,4,5,6,7,8,9 ..."
我的一般问题是如何在这种数据集上反转"聚集"的应用.
Ami*_*hli 28
哈德利的干预并不令人惊讶地完美......但是我在结束之后最终对语法进行了修改......所以为了它的价值,我发布完全可操作的代码(抱歉,我的语法与上面的有点不同):
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
Run Code Online (Sandbox Code Playgroud)
它们是相同的....如果你觉得它需要重新排序......
wide <- wide[,c(3, 4, 5, 6, 1)] ## Reorder and then remove "row" column
Run Code Online (Sandbox Code Playgroud)
并做了.
| 归档时间: |
|
| 查看次数: |
14100 次 |
| 最近记录: |