giegie
giegie

Reputation: 463

Add a column to dataframe in R based on grater/less than condition based on the values in existing columns

I have a dataframe and want to create a new column Z populated with a value of "tw" or "ok" for each record. If x > y, z = "ok" , IF x < y, z = "tw".

  x y 
a 1 2
b 2 3
c 5 1

result

  x y z
a 1 2 tw
b 2 3 tw
c 5 1 ok

Upvotes: 0

Views: 51

Answers (3)

Ronak Shah
Ronak Shah

Reputation: 388982

We can do this directly :

df$z <- c("tw", "ok")[(df$x > df$y) + 1]
df
#  x y  z
#a 1 2 tw
#b 2 3 tw
#c 5 1 ok

Not exactly clear what you want to do when x == y (above assigns "ok").


We can also use case_when from dplyr to assign values based on various condition.

library(dplyr)
df %>%
  mutate(z = case_when(x > y ~"ok", 
                       x < y ~"tw", 
                       TRUE ~ NA_character_))

data

df <- structure(list(x = c(1L, 2L, 5L), y = c(2L, 3L, 1L), z = c("tw", 
"tw", "ok")), row.names = c("a", "b", "c"), class = "data.frame")

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101383

Maybe you can try ifelse() like below

df <- within(df,z <- ifelse(x>y,"ok","tw"))

If you do not define the output for the case "x==y", maybe you should add the following line

df$z[df$x==df$y] <- NA

Upvotes: 4

LeroyFromBerlin
LeroyFromBerlin

Reputation: 395

alternatively you can do it on the dataframe directly:

# creation of dataframe
df = data.frame("x" = c(1, 2, 5), "y" = c(2, 3, 1))

# column creation of z
df$z[(df$x > df$y)] <- "ok"
df$z[(df$x < df$y)] <- "tw"

Upvotes: 4

Related Questions