简体   繁体   中英

Check if a column contains a sequence

I want to know, if i can check out if a column of a data frame starts with 0 or 1 and goes till the number of rows without breaking the sequence. Below is a sample data frame.

structure(list(X = 1:22, SNR = c(1.0035798429, 11.9438978154, 
NA, 3.2894877794, 4.0170266411, 1.6310522977, 1.6405414787, 1.6625412522, 
0.8489116253, 7.5312259672, 7.2832910726, 0.5732577083, NA, 0.8149754292, 
1.9981020389, 1.2477052103, 0.9960804911, 10.3402683931, 3.6328270728, 
2.5540496855, 41.96873985, 6.2035281045), ID = c(109L, 110L, 
111L, 112L, 113L, 114L, 116L, 117L, 118L, 119L, 120L, 121L, 123L, 
124L, 125L, 126L, 127L, 128L, 130L, 131L, 132L, 133L), SignalIntensity = c(6.8173738339, 
11.5459925418, NA, 9.7804203445, 9.8719842219, 9.0781857736, 
8.2289312163, 8.0435364446, 6.1793458315, 10.5581798932, 10.4745329822, 
4.1572943809, NA, 6.0451742752, 8.3100219509, 7.4558770659, 7.1464749962, 
11.4284386394, 9.6273795753, 9.6807417299, 13.3364944397, 10.4304671876
)), .Names = c("X", "SNR", "ID", "SignalIntensity"), class = "data.frame", row.names = c(NA, 
-22L))

How can i check the columns and return the index if present.

Edited: The sequence i am looking for is a natural sequence. Suppose if a data frame has 10 rows, the column if present should have a sequence 1,2,3,4,5,6,7,8,9,10 or may be like 0,1,2,3,4,5,6,7,8,9 . . So the sequence starts with 0 or 1 and goes till the number of rows with an increment of 1 for each row.

You could loop through the columns with sapply . Create a function to check whether there are any NAs. If not ( !any ), we get the difference ( diff ) between the adjacent element, check if all the element difference is 1 ( all(diff(x)==1 ) and ( & ) the first value of the column is 0 or 1 ( x[1] %in% 0:1 ). If there is any NA, the output for that column will be 'FALSE'.

 f1 <- function(x) {
          if(!any(is.na(x)))
         all(diff(x)==1) & x[1] %in% 0:1
         else FALSE}
 which(sapply(df, f1))
 #X 
 #1 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM