Help with gather()


I am new to R. I'd like to gather the iris data set into a table that looks like this:

Species Component Quantity Value
setosa Sepal Length 5.1
setosa Sepal Length 4.9

How should I use gather()? Thanks in advance for any help.


iris %>% 
  gather("Component", "Value", -Species)

See documentation here:

pivot_longer() is the new gather() and more intuitive.


Martin, thank you for this.

After gather(), I want to pipe into a separate() function, since I need to split the column containing "Sepal.Length" into 2 columns, using the fullstop as the separator. This is what I did:

tidy = iris %>%
  gather("Component", "Value", -Species) %>% 
  separate(Component, c("Component", "Quantity"), sep = ".") 

This gives me this error:

Expected 2 pieces. Additional pieces discarded in 600 rows [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...].

If remove the argument sep = "." from separate, the code runs fine.

Any idea what the issue may be?

Hi, thank you for the recommendation. I have to stick to gather() for now though.


iris %>% 
  as_tibble() %>% # not required
  gather("Component", "Value", -Species) %>% 
  separate(Component, c("Component", "Quantity"), sep = "\\.") 

You've stumbled on an issue introduced by regex. A single "." means any single character. The two "\" backslashes "escape" the expression meaning that the literal "." becomes the separator.

That works perfectly now, thanks!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.