I need a little help with a spread syntax...

Hi, I'm new to R. I'm practicing with the data "ChickWeight" that is in R.

I need a little help to understand how to code something that I want with the spread() function...
I want to understand how this function works so I can apply it to other databases...
I have watched lots of youtube videos, but I still don't get it right.

I want to dominate it, he, he, he...

# I have this
df %>% 
  select(Chick, Diet) %>% 
  group_by(Chick) %>% 

Which gives me two columns -Chick- & -Diet-

I want to spread the -Diet- column and the value that I want is the count of how many -Chicks- of every type have what type of -Diet-??

#This is what I code
df %>% 
+   select(Chick, Diet) %>% 
+   group_by(Chick) %>% 
+   count(Diet) %>% 
+   spread(key =  Diet, value =  count(Diet)) %>% 
+   View()
Error in View : no applicable method for 'count' applied to an object of class "c('integer', 'numeric')"

I want something like this:

Chick Diet 1 Diet 2 Diet 3

  1.         13.         12.          7
  2.          4.            9.           10
  3.          10.         22.          1  

I hope I'm explaining myself...

Thx for your help :pray:

You've already calculated the count, which is named n by default.

I've also removed an unnecessary stage:

df %>% 
  count(Chick, Diet) %>% 
  spread(key =  Diet, value =  n)

You'd probably be better off learning pivot_* syntax, which has superseded gather/spread:
Pivot data from long to wide — pivot_wider • tidyr (tidyverse.org)


Oh! now I see...

Thank you so much! :pray:

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.