Reputation: 3591
I have a dataframe
division | category
A | tools
A | work
B | tools
B | books
both columns are factor variables. how do I pivot the category columns so that I get:
division | tools | books | work
A 1 1
B 1 1
I tried using dplyr
wide <- df %>%
spread(division, category)
but I still get the same number of rows it hasn't collapsed them down to open per division?
Upvotes: 2
Views: 2088
Reputation: 887881
One option would be to create another column of 1 with transform
, and use that column as the value.var
in dcast
library(reshape2)
dcast(transform(df, ind=1), division~category, value.var='ind')
Or as @MichaelChirico mentioned, we can specify fun.aggregate
as length
dcast(df, division~category, length)
Or if we are using dplyr/tidyr
, mutate
the dataset to create the new column and then spread
from 'long' to 'wide'. spread
always needs the column that contains the value to put into the output data.frame
. This was not present in the example of the OP, and adding it solves the issue.
library(dplyr)
library(tidyr)
df %>%
mutate(ind=1) %>%
spread(category,ind)
Upvotes: 5