Subset rows based on “start and stop” strings

雨燕双飞 提交于 2019-12-24 08:18:42

问题


looking to write an R script that will search a column for a specific value and begin sub setting rows until a specific text value is reached.

Example:

    X1  X2 
[1,] "a" "1"
[2,] "b" "2"
[3,] "c" "3"
[4,] "d" "4"
[5,] "e" "5"
[6,] "f" "6"
[7,] "c" "7"
[8,] "k" "8"

What I'd like to do is search through X1 until the letter 'c' is found, and begin to subset rows until another letter 'c' is found, at which point the subset procedure would stop. Using the above example, the result should be a vector containing c(3,4,5,6,7).

Assume there will be no more than 2 rows where X1 equals 'c'

Any help is greatly appreciated.


回答1:


You can lookup where a value is with the function which, and use that as in index to get the values you are looking for. If you want everything from the first to the second "c", it would look like this:

indices <- which(df$X1=='c')
range <- indices[1]:indices[2]
df$X2[range]


来源:https://stackoverflow.com/questions/53711323/subset-rows-based-on-start-and-stop-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!