如何在R中返回数据框中两个位置之间特定值的位置

zc0qhyus  于 2023-06-27  发布在  其他
关注(0)|答案(1)|浏览(111)

我试图写一个代码,将返回一个 Dataframe 内的两个范围之间的特定值的所有位置。为了进一步解释,让我们假设,我在一个 Dataframe 中有0,它有50行,从1:36开始。假设想要一个解决方案,它只会在行12:36之间查找,并返回零的位置。
我正在使用的 Dataframe 如下所示:

structure(list(`Key Figures` = c("Jan-19", "Feb-19", "Mar-19", 
"Apr-19", "May-19", "Jun-19", "Jul-19", "Aug-19", "Sep-19", "Oct-19", 
"Nov-19", "Dec-19", "Jan-20", "Feb-20", "Mar-20", "Apr-20", "May-20", 
"Jun-20", "Jul-20", "Aug-20", "Sep-20", "Oct-20", "Nov-20", "Dec-20", 
"Jan-21", "Feb-21", "Mar-21", "Apr-21", "May-21", "Jun-21", "Jul-21", 
"Aug-21", "Sep-21", "Oct-21", "Nov-21", "Dec-21"), SKU = c("XYZ_20645", 
"XYZ_20645", "XYZ_20645", "XYZ_20645", "XYZ_20645", "XYZ_20645", 
"XYZ_20645", "XYZ_20645", "XYZ_20645", "XYZ_20645", "XYZ_20645", 
"XYZ_20645", "XYZ_20645", "XYZ_20645", "XYZ_20645", "XYZ_20645", 
"XYZ_20645", "XYZ_20645", "XYZ_20645", "XYZ_20645", "XYZ_20645", 
"XYZ_20645", "XYZ_20645", "XYZ_20645", "XYZ_20645", "XYZ_20645", 
"XYZ_20645", "XYZ_20645", "XYZ_20645", "XYZ_20645", "XYZ_20645", 
"XYZ_20645", "XYZ_20645", "XYZ_20645", "XYZ_20645", "XYZ_20645"
), `Baseline history Q` = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 10, 
10, 0, 100, 0, 30, 0, 50, 70, 280)), row.names = c(NA, -36L), class = c("tbl_df", 
"tbl", "data.frame"))

我写的代码如下:

Pd <- read_excel("X:/X/X/X- X/X/X.xlsx",
                             sheet = "X")

Start_Location <- head(which(Pd$`Baseline history Q`!=0),1)
End_Location <- tail(which(Pd$`Baseline history Q`!=0),1)

which(Pd$`Baseline history Q`!=0)

which()函数返回所有非零值和位置,但我不确定如何使其在Start_location : End_Location范围内。共享位置,如下所示:

print(Start_Location)
[1] 12
print(End_Location)
[1] 36

预期输出是包含0的位置,如下所示:

有人可以帮助我,让我知道,如何正确地做?

juzqafwq

juzqafwq1#

这个可以吗

Pd <- data.frame(`Baseline history Q` = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
                                          10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 10, 
                                          10, 0, 100, 0, 30, 0, 50, 70, 280), check.names = FALSE)

(start_z <- head(which(Pd$`Baseline history Q`!=0),1))
#> [1] 12
(end_z   <- tail(which(Pd$`Baseline history Q`!=0),1))
#> [1] 36

which_z <- which(Pd$`Baseline history Q` == 0)
which_z[which_z %in% start_z:end_z]
#> [1] 26 29 31 33

创建于2023-06-21使用reprex v2.0.2

相关问题