如果R

时间:2018-02-23 13:51:04

标签: r if-statement

我有一个ifelse语句,并希望每次满足条件时将变量增加1,如果条件是,则减去整个计数-count不满足。

df = data.frame(indicator= c(60,61,58,40,70,80))

position = 0
df$sig = ifelse((df$indicator > 60), 
       (position = position + 1), 
       -position)

答案看起来像这样

df = data.frame(indicator= c(60,61,58,40,70,80),
                sig = c(0,1,0,0,1,2))

这是为了跟踪交易头寸(如果超过60则买入,如果低于卖出,则跟踪​​,但跟踪头寸有多大。

我怎样才能在R?

中这样做

4 个答案:

答案 0 :(得分:4)

也许是这样的,来自dplyr包的rleiddata.table

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

输出:

  indicator sig
1        60   0
2        61   1
3        58   0
4        40   0
5        70   1
6        80   2

或者,只有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)]

希望这有帮助!

答案 1 :(得分:3)

使用香草R,您可以使用rleave + 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))

结果:

> df
  indicator sig
1        60   0
2        61   1
3        58   0
4        40   0
5        70   1
6        80   2

答案 2 :(得分:0)

count = 0
count = count + sum(ifelse(df$colour == "green", 1, 0))

但是你可以更直接地做到这一点:

count = sum(df$colour == "green")

这是有效的,因为TRUE等于1,当你求和时,FALSE等于0。

答案 3 :(得分:0)

那将是:

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)