Reputation: 55
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
Upvotes: 2
Views: 15622
Reputation: 13827
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]
Upvotes: 0
Reputation: 140
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
Upvotes: 2
Reputation: 887941
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
Upvotes: 11