I am learning tidyr and doing a small exercise to transform iris data set from wide to long.
The original data set:
Species Sepal.Length Sepal.Width Petal.Length Petal.Width
1 setosa 5.1 3.5 1.4 0.2
2 setosa 4.9 3.0 1.4 0.2
3 setosa 4.7 3.2 1.3 0.2
4 setosa 4.6 3.1 1.5 0.2
5 setosa 5.0 3.6 1.4 0.2
6 setosa 5.4 3.9 1.7 0.4
The resulting data set I want:
Species Part Length Width
1 setosa Petal 1.4 0.2
2 setosa Petal 1.4 0.2
3 setosa Petal 1.3 0.2
4 setosa Petal 1.5 0.2
5 setosa Petal 1.4 0.2
6 setosa Petal 1.7 0.4
The code I wrote for manipulating data set:
iris_re <- iris[,c(5,1,2,3,4)]
iris.wide <- iris_re %>%
gather(key = "flower_att", value = "measurement",
-Species) %>%
separate(flower_att, into = c("Part","Method")) %>%
spread(Method,measurement)
But the final line of spread() gives me an error:
Error: Each row of output must be identified by a unique combination of keys. Keys are shared for 400 rows:
I did not expect this happen and I am still struggling with it. Thank you!
pivot_wideralternative helps), including this one on the same dataset