Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

regex - How to search and extract in a dataframe in #R using a pattern that includes moving from columns and rows?

I would like to search and extract from a big dataframe in R a number that is located in different places but is always located one column and one row more than the word "LAYER".

I have tried to do it but I can only find a way to extract "LAYER" with a filter using the dplyr package but maybe I need to use something different.

For example, in the following table I would like to extract the 2 and the 3.65 that are bold in the dataframe.

X1 X2 X3
LAYER 1 NA
190 2 NA
NA 20 1200
NA 30 2200
... ... ...
LAYER 2 NA
180 3.65 NA
NA 50 1850
NA 95 2300
... ... ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can get the indices where X1 is 'LAYER' and extract next X2 value.

inds <- which(data$X1 == 'LAYER')
result <- data.frame(X2 = data$X2[inds + 1])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...