【发布时间】:2020-09-21 18:49:44
【问题描述】:
我对 R 和进行分析的学习方法仍然很陌生。我有一个 df,我想根据“x9”列计算连续的赢/输。这显示了输入交易的收益/损失(正值或负值)。我确实找到了一些有助于分配符号、符号滞后和更改的代码的帮助,但是,我正在寻找计数器来计算连续胜利,直到实现失败然后重置,然后计算连续失败直到实现胜利.总体而言,我正在寻求帮助来调整计数器以在连续赢/输中断时重置。我在下面有一些示例代码和附加的 .png 来解释我的想法
#Read in df
df=vroom::vroom(file = "analysis.csv")
#Filter df for specfic order types
df1 = filter(df, (x3=="s/l") |(x3=="t/p"))
#Create additional column to tag wins/losses in df1
index <- c("s/l","t/p")
values <- c("Loss", "Win")
df1$col2 <- values[match(df1$x3, index)]
df1
#Mutate df to review changes, attempt to review consecutive wins and losses & reset when a
#positive / negative value is encountered
df2=df1 %>%
mutate(sign = ifelse(x9 > 0, "pos", ifelse(x9 < 0, "neg", "zero")), # get the sign of the value
sign_lag = lag(sign, default = sign[9]), # get previous value (exception in the first place)
change = ifelse(sign == sign_lag, 1 , 0), # check if there's a change
series_id = cumsum(change)+1) %>% # create the series id
print() -> dt2
【问题讨论】:
-
请不要发布代码/数据/错误的图像:它不能被复制或搜索 (SEO),它会破坏屏幕阅读器,并且它可能不适合某些移动设备。参考:meta.stackoverflow.com/a/285557(和xkcd.com/2116)。请直接包含代码、控制台输出或数据(例如,
dput(head(x))或data.frame(...))。 -
拥有
df2 = df1 %>% ... %>% print() -> dt2似乎很奇怪。它们应该是等价的 (identical(df2, dt2)),所以这里没有损失,但只是......奇怪。 -
你说得对,我只是在实验室里尝试不同的方法。它们确实是一样的。感谢您对此的快速回复和帮助。
标签: r