library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(reprex)
rm (list = ls())
a <- c("dog", "cat", "dog", "camel", "dog", "cat", "dog")
b <- c(1,0,1,1,1,0,1)
x <- data.frame(a,b)
x
#> a b
#> 1 dog 1
#> 2 cat 0
#> 3 dog 1
#> 4 camel 1
#> 5 dog 1
#> 6 cat 0
#> 7 dog 1
attach(x)
#> The following objects are masked _by_ .GlobalEnv:
#>
#> a, b
#y <- summarise(group_by(x,a), sum(b))
#y
#x
x %>% group_by(a) %>% summarise(sum_animal = sum(b))
#> # A tibble: 3 x 2
#> a sum_animal
#> <fct> <dbl>
#> 1 camel 1
#> 2 cat 0
#> 3 dog 4
x$c <- x %>% group_by(a) %>% summarise(sum_animal = sum(b))
#> Error in `$<-.data.frame`(`*tmp*`, c, value = structure(list(a = structure(1:3, .Label = c("camel", : replacement has 3 rows, data has 7
#Would like to create a new vector c in dataframe x which would have the values of the total frequency of an animal
#in vector b for every value (animal name) in vector a. So c should have the values 4,0,4, 1,4,0, 4
Created on 2019-08-31 by the reprex package (v0.2.1)