I have this dataset -
print(df)
object group
1 apple A
1 banana B
1 pear A
1 robot C
print(df2)
object group
1 apple A
1 apple B
1 apple A
1 robot C
1 robot C
1 robot C
1 banana C
I'd like to count the number of times each value shows up in another data set, which looks exactly the same but draws data from a different time period. The other dataset is called df2
.
I used this code -
x <- df %>%
mutate(reference = length(df2[df2$object == object,]$object))
It gave me this error: longer object length is not a multiple of shorter object length
.
It works when I run this outside of dplyr, like this -
object <- "apple"
length(df2[df2$object == object,]$object)
Can I do a relative reference like that, including object
in the filter?
If you need a
tidyverse
option, we can usemap_dbl
which can be also calculated with
sum
So in
mutate
we can addThe similar base R option is
sapply
We can do this in
data.table
From my comment: dplyr functions work on the whole column taken as a vector. Try
As you said,
ungroup
will be needed, unless you plan on doing further row-wise operations.