0

I have a dataframe that looks like this


plots <- data.frame(plot=c("A", "A", "A", "B", "B", "C", "C", "C"), 
                   value= c(1,1,1,2,2,3,3,3))


 plot value
1  A    1     
2  A    1
3  A    1
4  B    2
5  B    2
6  C    3
7  C    3
8  C    3

I want to have a third column sum where I would sum all the values from the same plots, so it would look like this:

 plot value sum
1  A    1    3   
2  A    1    3
3  A    1    3
4  B    2    4
5  B    2    4
6  C    3    9
7  C    3    9
8  C    3    9

starski
  • 141
  • 6

3 Answers3

2

With tidyverse:

library(tidyverse)
plots %>% as_tibble() %>% group_by(plot) %>% mutate(sum=sum(value))

returns:

# A tibble: 8 × 3
# Groups:   plot [3]
  plot  value   sum
  <chr> <dbl> <dbl>
1 A         1     3
2 A         1     3
3 A         1     3
4 B         2     4
5 B         2     4
6 C         3     9
7 C         3     9
8 C         3     9
Jan Z
  • 171
  • 3
1
> ave(plots$value,plots$plot,FUN=sum)
[1] 3 3 3 4 4 9 9 9
user2974951
  • 9,535
  • 1
  • 17
  • 24
  • Doesn't work on my code, I thought about using an if statement but I don't know how to set it up. I basically wanna sum up the values of the same plots. So in the case of the example I gave, I want a third columns that sums up all the values with the same plot. – starski Nov 30 '22 at 12:55
  • 1
    @starski What doesn't work? I used it on the code you provided and it works. Did you save the output into a column? – user2974951 Nov 30 '22 at 12:56
  • My bad! It worked out. – starski Nov 30 '22 at 13:06
-1
plots%>%group_by(plot)%>%summarise(n=sum(value),plot,.groups="drop")%>%as.data.frame()

  plot n
1    A 3
2    A 3
3    A 3
4    B 4
5    B 4
6    C 9
7    C 9
8    C 9
ALİ AA
  • 1
  • 2
  • 1
    Hello ALİ, the question author has indicated that they want the output to have the same number of rows as the input. Thus, `mutate` should be used. To low quality answer reviewers: this answer is clearly *technically incorrect* but it also clearly attempts to answer the question asked. – Ian Campbell Nov 30 '22 at 22:59