2

New to R, so bear with me. I have a dataframe with values

x y
1 2
4 4
5 3
6 0 

I want to create a third column that indicates with TRUE or FALSE whether a value in column y is 0.

x y z
1 2 TRUE
0 4 TRUE
5 3 TRUE
6 0 FALSE
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Sam Nipius
  • 55
  • 1
  • 1
  • 7

3 Answers3

11

The > compares the lhs and rhs to get a logical vector. By assigning the output as a new column ('z'), we create the new column in the original dataset 'df1'.

df1$z <- df1$y > 0
akrun
  • 874,273
  • 37
  • 540
  • 662
2

You can also always create one column with an "empty" value in order to avoid if-else loop.

Something like this could work as well (though the solution proposed above is of course better):

df$z <- "False"
df$z[df$y > 0] <- "True"

Quotes can be escaped if you wish a logical variable rather than a string

DenisK
  • 140
  • 1
  • 8
0

An alternative solution that is faster (although this only becomes a critical issue when working with large datasets)

library(data.table)

setDT(df1)

df1[, z := y > 0]
rafa.pereira
  • 13,251
  • 6
  • 71
  • 109