I have a data frame containing threshold values for different data types:
threshold <- c(5, 10)
type <- c("type1", "type2")
threshold.df <- data.frame(type, threshold)
This gives:
> threshold.df
type threshold
1 type1 5
2 type2 10
In another data frame, I have:
x <- rep(1:30, 2)
y <- x^2
type <- rep(c("type1", "type2"), each = 30)
my.df <- data.frame(x, y, type)
Which gives:
> head(my.df)
x y type
1 1 1 type1
2 2 4 type1
3 3 9 type1
4 4 16 type1
5 5 25 type1
6 6 36 type1
Now, I want to replace all y values of type 1 where x is lower that the threshold by 0.
Using dplyr, I was thinking about something like my.df %>% group_by(type) %>% mutate(y = somefunction)
.
But then I'm stuck for the function implementation.
I know it can also be done using ave function, but end up with the same problem.
I would know how to do it with a loop, but I'm sure there are better ways with R.