Reputation: 600
I'm sure I'm missing something obvious here. I want to add rownumbers to a summarized table, but dplyr cycles/repeats the rownumbers per my earlier grouping. I thought I had ungrouped it, but clearly I'm missing something. I want each line in indexed to have a unique rownumber.
#Make sample data
Species <- c("A", "B", "C","D")
Animal <- c(1:100)
Day <-c(1:10)
P <- sample(1:100, 300, replace = TRUE)
F <- sample(1:100, 300, replace = TRUE)
C <- sample(1:100, 300, replace = TRUE)
df <- data.frame(Species,Animal,Day, P, F, C)
#Summarize by columns
by_day <- df %>%
group_by(Species, Animal, Day) %>%
summarize(ptot = sum(P), ftot = sum(F), ctot = sum(C))
#Here's where I suspect the problem lies
ungroup(by_day)
#This line produces repeating id numbers, where as I want each line to have a unique one.
indexed <- mutate(by_day, id = row_number())
Upvotes: 1
Views: 6653
Reputation: 740
If you simply reformat a grouped data frame as data frame via as.data.frame()
, it is also automatically ungrouped.
Upvotes: 0
Reputation: 214957
It seems you assume ungroup
will modify by_day
in place, which it doesn't; You need to make sure you pass an ungrouped data frame to mutate
:
mutate(ungroup(by_day), id = row_number())
# A tibble: 100 x 7
# Species Animal Day ptot ftot ctot id
# <fctr> <int> <int> <int> <int> <int> <int>
# 1 A 1 1 266 262 45 1
# 2 A 5 5 84 201 159 2
# 3 A 9 9 141 149 244 3
# 4 A 13 3 94 142 157 4
# 5 A 17 7 188 138 142 5
1) before ungroup
:
by_day
# A tibble: 100 x 6
# Groups: Species, Animal [?] <<<<<<<<<<<<<<<<<<<<
# Species Animal Day ptot ftot ctot
2) ungroup
returns a data frame that is not grouped:
ungroup(by_day)
# A tibble: 100 x 6
# Species Animal Day ptot ftot ctot
3) but it doesn't modify by_day
, it's still grouped
by_day
# A tibble: 100 x 6
# Groups: Species, Animal [?] <<<<<<<<<<<<<<<<<<<<
# Species Animal Day ptot ftot ctot
Upvotes: 6