I want to compare every row in a column in a dataframe to a single vector.
temp_df <- data.frame(x = c(3, 2, 1),
y = c(4, 4, 2))
> temp_df
x y
1 3 4
2 2 4
3 1 2
I want to compare each y
to every single x
to see if y
is greater than all of the x
values. If the y
is not greater than all x
values then I want to return FALSE
.
I can achieve this by looping through my dataframe but I want to avoid that. This is the result I am seeking:
> temp_df
x y z
1 3 4 TRUE
2 2 4 TRUE
3 1 2 FALSE
I am trying to do this is base R but am open to other solutions also.
CodePudding user response:
We can use
temp_df$z <- sapply(temp_df$y, function(u) all(u > temp_df$x))
temp_df$z
[1] TRUE TRUE FALSE