简体   繁体   中英

How apply a function in data frame with if/ lessthan statement in R?

I have a data frame looks like the following:

df<- data.frame(
  X1 = seq(from = 7, to = 25, by = 2),
  X2 = c(7,  10 ,11, 12, 16, 17, 20, 24, 2, 30),
  X3 = 2:11
)

I want to substitute column X3 with the following logic

if X1 lees than x2 then X3=0

library(dplyr)
df %>% 
    mutate(X3 = ifelse(X1 < X2, 0, X3))

Output:

   X1 X2 X3
1   7  7  2
2   9 10  0
3  11 11  4
4  13 12  5
5  15 16  0
6  17 17  7
7  19 20  0
8  21 24  0
9  23  2 10
10 25 30  0

You can do -

df$X3[df$X1 < df$X2] <- 0
df

#   X1 X2 X3
#1   7  7  2
#2   9 10  0
#3  11 11  4
#4  13 12  5
#5  15 16  0
#6  17 17  7
#7  19 20  0
#8  21 24  0
#9  23  2 10
#10 25 30  0
df %>% mutate(X3 = ifelse(X1 < X2,0,X3))

我们可以用

df$X3 <- with(df, X3 * (X1 >= X2))

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