首页 > 解决方案 > 给定R中的特定条件,如何找到最小的正负值?

问题描述

我有一个看起来像这样的数据框:

数据框图片

highopen_percent_change <- c(0.285, -2.156, 0.030, -0.184, -0.005, 0,092, -0.092, 0, -0.0563, -0.020, -0.174, -0.492, 0.201, -0.005)
IDcombinatie_nr <- c(47, 41, 42, 45, 41, 42, 48, 32, 44, 48, 32, 48, 32, 48, 28, 12, 32)
df <- data.frame(highopen_percent_change, IDcombinatie_nr)

highopen_percent_change在这个数据框中,我想知道per的最小正负值IDcombinatie_nr。所以IDcombinatie_nr我想知道最小的正值和负值highopen_percent_change是多少。该值不应为零,因为highopen_percent_change在我的数据框中某些值为零。

所以,这就是我想要的:

对于 47,最低正值为 0.05,最低负值为 -0.1。

对于 41,最低正值为 0.02,最低负值为 -0.4。

对于 42,最低正值为 0.3,最低负值为 -0.2。

我希望你能帮助我。

标签: r

解决方案


R base中,您可以使用tapply加子集:

min.pos <- tapply(df$highopen_percent_change[df$highopen_percent_change > 0],
                 df$IDcombinatie_nr[df$highopen_percent_change > 0], min)

min.neg <- tapply(df$highopen_percent_change[df$highopen_percent_change < 0],
                 df$IDcombinatie_nr[df$highopen_percent_change < 0], min)

推荐阅读