[英]Increase the value of a variable in a vector using ifelse if R
I have an ifelse
statement and want to increase the the variable by 1
each time the condition is met and drop the count to by subtracting the entire count -count
if the condition is not met. 我有一条ifelse
语句,想在每次满足条件时将变量增加1
如果不满足条件,则通过减去整个count -count
来减少计数。
df = data.frame(indicator= c(60,61,58,40,70,80))
position = 0
df$sig = ifelse((df$indicator > 60),
(position = position + 1),
-position)
The answer would look like this 答案看起来像这样
df = data.frame(indicator= c(60,61,58,40,70,80),
sig = c(0,1,0,0,1,2))
This is to keep track of a trading position (buy if over 60 and sell if under but keep track of how big the position is. 这是为了跟踪交易头寸(如果超过60,则买入;如果低于60,则卖出,但要跟踪头寸的大小。)
How can I do this in R? 我如何在R中做到这一点?
Maybe like this, with dplyr
and rleid
from the data.table
package: 也许像这样,使用data.table
包中的dplyr
和rleid
:
df = data.frame(indicator= c(60,61,58,40,70,80))
library(dplyr)
library(data.table)
df %>%
group_by(group = rleid(indicator > 60)) %>%
mutate(sig = cumsum(indicator > 60)) %>%
ungroup() %>%
select(-group) %>%
as.data.frame
Output: 输出:
indicator sig
1 60 0
2 61 1
3 58 0
4 40 0
5 70 1
6 80 2
Or alternatively, only with data.table
: 或者,仅使用data.table
:
df = data.frame(indicator= c(60,61,58,40,70,80))
library(data.table)
setDT(df)[,sig := cumsum(indicator > 60), rleid(indicator > 60)]
Hope this helps! 希望这可以帮助!
With vanilla R, you can use rle
and ave
+ cumsum
: 香草R,您可以使用rle
和ave
+ cumsum
:
rl <- rle(df$indicator > 60)
rl$values <- seq_along(rl$values)
df$sig <- ave(df$indicator, inverse.rle(rl), FUN = function(x) cumsum(x > 60))
The result: 结果:
> df
indicator sig
1 60 0
2 61 1
3 58 0
4 40 0
5 70 1
6 80 2
count = 0
count = count + sum(ifelse(df$colour == "green", 1, 0))
However you could more directly just do this: 但是,您可以直接执行以下操作:
count = sum(df$colour == "green")
This works because TRUE is equal to 1 and FALSE is equal to 0 when you sum them. 之所以起作用,是因为将它们相加时,TRUE等于1,而FALSE等于0。
That would be: 那将是:
position <- 0
df <- data.frame(indicator= c("60","61","58","40","70","80"))
df$indicator <- as.numeric(df$indicator)
df_sum <- sum(df$indicator)
position <- ifelse(df_sum > 60, position + 1, position -1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.