[英]How do I create an XTS of dummy variables from another XTS?
Suppose I have the following xts...假设我有以下 xts ...
a <- c(1,-1,2,-2)
b <- c(-1,-2,3,4)
x <- xts(cbind(a,b),order.by = as.Date(c("2015-01-02","2015-01-05","2015-01-06","2015-01-07")))
x
This gives you...这给你...
a b
2015-01-02 1 -1
2015-01-05 -1 -2
2015-01-06 2 3
2015-01-07 -2 4
I want to create an xts of dummy variables that take the value 1 when the value is greater than 0 and 0 and when value is less than or equal to 0. So I'd like to get this...我想创建一个 xts 的虚拟变量,当值大于 0 和 0 以及值小于或等于 0 时取值 1。所以我想得到这个......
a b
2015-01-02 1 0
2015-01-05 0 0
2015-01-06 1 1
2015-01-07 0 1
I tried the following code but it didn't work...我尝试了以下代码,但它没有工作......
y <- ifelse(x>0,1,0)
y
Here is an option where we convert the logical to binary with as.integer
and assign the results back to the original dataset这是一个选项,我们使用as.integer
将逻辑转换为二进制并将结果分配回原始数据集
x[] <- as.integer(x > 0)
Or using arithmetic或使用算术
(x > 0) * 1
# a b
#2015-01-02 1 0
#2015-01-05 0 0
#2015-01-06 1 1
#2015-01-07 0 1
Or another option is或者另一种选择是
(x > 0) + 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.