0

I want to reshape iris data in R from 5 columns to 4 columns. The final output should be have columns:

  1. Species
  2. Part
  3. Length
  4. Width

The 'Part' column should include 'Petal' and 'Sepal'

The code which I tried as below gave an error "Error: Duplicate identifiers for rows"

iris_new <- iris[c(5, 1:4)] %>% 
gather(part_measure, value, -Species) %>%
separate(part_measure, c("part", "measure"), "[.]") %>%
spread(measure, value)

Please correct me, thanks in advance.

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
feb
  • 79
  • 1
  • 1
  • 8

1 Answers1

2

You just need an ID variable to uniquely identify each row.

iris_new <- iris[c(5, 1:4)] %>% 
  mutate(id = 1:nrow(iris)) %>% 
  gather(part_measure, value, -Species, -id) %>%
  separate(part_measure, c("part", "measure"), "[.]") %>%
  spread(measure, value) %>% View()
A Toll
  • 507
  • 5
  • 13