根据另一列的行值有条件地返回一向量的某些行值。

huangapple go评论108阅读模式
英文:

Conditionally returning a vector of some row values based on another column's row values

问题

我正在尝试在“lab”列的相应值为“A”时将“diff”列的行作为向量返回。但条件是,对于“BB”,不仅会删除相应的diff值,还会跳过上下行的两个即时值。

从上述示例中,预期的输出如下:

> res
[1]  0.0314439 -1.2708040  0.4045876 -0.1069435

请问还有其他需要帮助的地方吗?谢谢!

英文:

Here is a reproducible data set:

set.seed(55);
data <- rnorm(12);
dates <- as.POSIXct("2019-03-18 10:30:00", tz = "CET") + 0:(length(data)-1)*60;

R <- xts(x = data, order.by = dates) %>%
  sample(size = 10) %>%
  fortify.zoo()

colnames(R) <- c("Time", "Rf");
R$lab <- "A"
R$lab[c(5, length(R$lab))] <- "BB"
R$diff <- c(NA, diff(R$Rf))

Output looks like:

> R
                  Time           Rf lab       diff
1  2019-03-18 10:30:00  0.120139084   A         NA
2  2019-03-18 10:32:00  0.151582984   A  0.0314439
3  2019-03-18 10:33:00 -1.119221005   A -1.2708040
4  2019-03-18 10:34:00  0.001908206   A  1.1211292
5  2019-03-18 10:36:00 -0.505343855  BB -0.5072521
6  2019-03-18 10:37:00 -0.099234393   A  0.4061095
7  2019-03-18 10:38:00  0.305353199   A  0.4045876
8  2019-03-18 10:39:00  0.198409703   A -0.1069435
9  2019-03-18 10:40:00 -0.048910950   A -0.2473207
10 2019-03-18 10:41:00 -0.843233767  BB -0.7943228

I am trying to return the rows of column "diff" as a vector when the corresponding value of "lab" column is "A". But the condition is, for "BB" not only the corresponding diff value is dropped but also the two immediate values from upper and lower rows are also skipped.

Of the above example, following output is expected:

> res
[1]  0.0314439 -1.2708040  0.4045876 -0.1069435

Can you kindly help? Thanks

答案1

得分: 2

你可以尝试

inds <- which(R$lab == "BB")
R$diff[-unique(c(inds - 1, inds, inds + 1))]

或者如@Rui Barradas提到的

R$diff[-sapply(inds, `+`, -1:1)]
英文:

You can try

inds &lt;- which(R$lab == &quot;BB&quot;)
R$diff[-unique(c(inds - 1, inds, inds + 1))]

Or as @Rui Barradas mentioned

R$diff[-sapply(inds, `+`, -1:1)]

huangapple
  • 本文由 发表于 2020年1月3日 18:31:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/59576978.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定