简体   繁体   中英

r function to return column number if/when a certain criteria is met

I have a dataframe that looks like this:

df<-data.frame(H0=c(35.4, NA, 36.0, 36.4), H1=c(32.3, 32.0, 34.3, 33.5), 
           H2=c(33.4, 31.5, 33, 34.2), H3=c(32.9, 33.0, 34.0, 33.0),
           H4=c(32.8, NA, 34.5, 33.2))

I need a function that will search through every row and return the number (not name) of the column where the value first appears as <=33.0.

NA is ignored so I would expect:

[1] 2 2 3 4

Your question doesn't say how you want to deal with NA s or rows that don't have any < 33. max.col might be good enough for your task:

R>df
    H0   H1   H2   H3   H4
1 35.4 32.3 33.4 32.9 32.8
2   NA 32.0 31.5 33.0   NA
3 36.0 34.3 33.0 34.0 34.5
4 36.4 33.5 34.2 33.0 33.2
R>max.col(df <= 33, ties.method="first")
[1]  2 NA  3 4

Edit: And to handle NA s, replacing them with Inf should do the trick:

R>max.col( `[<-`(df, is.na(df), value=Inf) <= 33, ties.method="first")
[1] 2 2 3 4

You can try match , which returns the index of the first occurrence.

NA is ignored because the default setting for nomatch is set to NA_integer_

> apply(df, 1, function(x) match(TRUE, x <= 33.0))
# [1] 2 2 3 4

If you want to ignore NAs and put an NA if no value was found,

rowSearcher <- function(df) {

  colNumbers <- numeric(0)         # Vector of column numbers to output

  for (r in 1:ncol(df)) {          # Loop through the rows
    for (c in 1:ncol(df)) {        # Loop through the columns

      if (!is.na(df[r, c]) && df[r, c] <= 33.0) {
        colNumbers <- c(colNumbers, c)
        break 
      }

      if (c == ncol(df))          # Add an NA if no value was found
        colNumbers <- c(colNumbers, NA)
    }
  }
  return(colNumbers)
}

You could also use:

apply(df,1,function(x) Position(function(y) y <=33 & !is.na(y), x))
#[1] 2 2 3 4

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