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

Gal*_*le2 3 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
Run Code Online (Sandbox Code Playgroud)

Ric*_*rta 10

我认为你在寻找的是

 sum(diff(sign(X)) != 0)
Run Code Online (Sandbox Code Playgroud)

X在你的情况下,dat$Direction你试图计算符号变化的向量在哪里.



如果要计算Path,可以使用该by函数,或将您转换data.frame为a 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]
Run Code Online (Sandbox Code Playgroud)

编辑(重新评论factors):

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

DT[, Direction := as.numeric(Direction)]
Run Code Online (Sandbox Code Playgroud)

结果:

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
Run Code Online (Sandbox Code Playgroud)


Tyl*_*ker 2

这是一种使用sign和 的方法rle,正如贾斯汀所建议的:

length(rle(sign(Test$Direction))[[1]])
Run Code Online (Sandbox Code Playgroud)

编辑
我一开始可能误解了。也许这更接近你想要的:

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