With
df <- data.frame(v1=c(1:5), v2=c(9,32,6,17,11))
I need to add a new column v3 with value 1 or 0 based on whether values in v2 are larger than 10 or not so that:
df
v1 v2 v3
1 1 9 0
2 2 32 1
3 3 6 0
4 4 17 1
5 5 11 1
Is there such thing like x ? y : z in R? If not, what's a good way to solve the above? Thanks!
ifelse(..)
comes closest:
R> df <- data.frame(v1=c(1:5), v2=c(9,32,6,17,11))
R> df$v3 <- ifelse(df$v2 > 10, 1, 0)
R> df
v1 v2 v3
1 1 9 0
2 2 32 1
3 3 6 0
4 4 17 1
5 5 11 1
R>
I don't know whether ifelse is faster, but this is easier to read:
> d <- data.frame(v1=c(1:5), v2=c(9,32,6,17,11))
> d$v3 <- as.numeric(d$v2 > 10)
> d
v1 v2 v3
1 1 9 0
2 2 32 1
3 3 6 0
4 4 17 1
5 5 11 1
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.