繁体   English   中英

计算值变化与R符号的次数

[英]Counting the number of times a value change signs with R

我对R很新,但我很鼓励,因为我发现虽然我不是程序员,但却可以访问它。 我试图解决以下问题:我需要计算值更改在列中签名的次数,然后按路径对结果进行排序(表格的示例如下 - 路径是一个因素)。 我可以想象一下我最终得到它们后如何对数据进行排序,但还没有弄清楚+符号变成次数的计数 - 而且 - 符号变为+ 1。 有什么建议吗?

Test <- structure(list(Path = c(1L, 1L, 1L, 2L, 2L, 2L), Direction = c(-3.84089, 
-1.12258, 1.47411, -1.47329, 5.4525, 10.161)), .Names = c("Path", 
"Direction"), class = "data.frame", row.names = c(NA, -6L))
head(Test)
#>   Path    Direction
#> 1    1     -3.84089
#> 2    1     -1.12258
#> 3    1      1.47411
#> 4    2     -1.47329
#> 5    2      5.4525
#> 6    2     10.161

我认为你在寻找的是

 sum(diff(sign(X)) != 0)

其中X是向量,在您的情况下,您尝试计算符号更改的dat$Direction



如果data.frame Path计算,可以使用by函数,或将data.frame转换为data.table并使用内置by功能。

例:

假设X是您的原始data.frame

 # I'm adding another row to the data, just to show that it works # (ie, giving the two Path values a different number of rows) X <- rbind(X, c(2, -5)) # convert to a data.table library(data.table) DT <- data.table(X) # count the number of changes, per path DT[, changes := sum(diff(sign(Direction)) != 0), by=Path] 

编辑(重新评论factors ):

如果Direction是一个factor ,则需要先将其转换为numeric 你可以使用

# I'm adding another row to the data, just to show that it works 
#    (ie, giving the two Path values a different number of rows)
X <- rbind(X, c(2, -5))

# convert to a data.table
library(data.table)
DT <- data.table(X)

# count the number of changes, per path
DT[, changes := sum(diff(sign(Direction)) != 0), by=Path]

结果:

 DT Path Direction changes 1: 1 -3.84089 1 2: 1 -1.12258 1 3: 1 1.47411 1 4: 2 -1.47329 2 5: 2 5.45250 2 6: 2 10.16100 2 7: 2 -5.00000 2 

这是使用signrle一种方法,Justin建议:

length(rle(sign(Test$Direction))[[1]])

编辑
起初我可能误会了。 也许这更接近你想要的:

vals <- tail(rle(sign(Test$Direction))[[-1]], -1)
sum(vals > 0) # neg to pos
sum(vals < 0) # pos to neg

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM