2
votes

I want to have the following code from data.table in a dplyr way:

library(tidyverse)
library(data.table)

Iris <- as.data.table(iris)

Iris[, .(m = mean(Sepal.Width[Sepal.Width < 3])), Species]

This is what I have so far:

Iris %>% 
  group_by(Species) %>% 
  summarise(m = mean(Sepal.Width))

But I do not know where I can place my condition Sepal.Width < 3.

1

1 Answers

5
votes

It is the same way as in data.table or in base R, create the logical vector (Sepal.Width < 3), use that to subset the column with [ and get the mean of the subset of values

library(dplyr)
Iris %>% 
  group_by(Species) %>%
  summarise(m = mean(Sepal.Width[Sepal.Width <3]))
# A tibble: 3 x 2
#  Species        m
#  <fct>      <dbl>
#1 setosa      2.60
#2 versicolor  2.61
#3 virginica   2.69