[英]Is there a similar way like x ? y : z in R?
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: 我需要根据v2中的值是否大于10添加一个值为1或0的新列v3,以便:
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 ? 有像x这样的东西吗? y : z in R?
y:R中的z? If not, what's a good way to solve the above?
如果没有,什么是解决上述问题的好方法? Thanks!
谢谢!
ifelse(..)
comes closest: ifelse(..)
最接近:
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: 我不知道ifelse是否更快,但这更容易阅读:
> 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.