简体   繁体   中英

Compare column to vector in R

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.

We can use

temp_df$z <- sapply(temp_df$y, function(u) all(u > temp_df$x))
temp_df$z
[1]  TRUE  TRUE FALSE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM