Reputation: 2489
I'm trying to add values to a new column based on values in another column. Using the iris data as an example my basic logic is "If iris$Sepal.Length > 5, then iris$size == 'TRUE'".
> head(iris, 2)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
Using the iris data as an example my basic logic is "If iris$Sepal.Length > 5, then iris$size == 'TRUE'" to produce:
Sepal.Length Sepal.Width Petal.Length Petal.Width Species size
1 5.1 3.5 1.4 0.2 setosa TRUE
2 4.9 3.0 1.4 0.2 setosa NA
I can subset the data, but can't get the syntax to pass a value back. Something like this?
subset(iris, iris$Sepal.Length >= 5) %>% iris$size == 'TRUE'
Upvotes: 0
Views: 1342
Reputation: 412
Either:
iris$size <- iris$Sepal.Length >= 5
Or if you want to go down the tidyverse route
iris %>% mutate(size = Sepal.Length >= 5)
Upvotes: 2
Reputation: 887158
Using dplyr
. The output of a logical expression is TRUE/FALSE
. It is better not to create a character output
library(dplyr)
iris %>%
mutate(size = Sepal.Length >=5)
Upvotes: 2
Reputation: 1376
You could do something like this using the ifelse
statement
iris$Size <- ifelse(iris$Sepal.Length >= 5, "TRUE", "FALSE")
Upvotes: 2
Reputation: 7592
iris$size[iris$Sepal.Length>=5] <- TRUE
This basically reads as "put TRUE into iris$size for those rows where iris$Sepal.Length is equal or greater than 5".
Upvotes: 2