简体   繁体   中英

how to find the column name of first and last negative value per each row in R

I want to find the column name of first and last row with negative value and add it to the data frame as two columns as "firststatus" and "laststatus". Here is an example:

structure(c(NA, NA, "11", "-8.01e-14", NA, "6", NA, "-3", "-7", NA, 
        NA, NA, NA, "3", "-5.0015e-8", NA, NA, NA, NA, "-4.5e+00", NA, "50.5", "51", 
        "51", "50.5", "53", "52"), .Dim = c(3L, 9L), .Dimnames = list(
          c("1001", "1002", "1003"), c("50", "50.5", "51", "51.5", 
                                       "52", "52.5", "53", "firststatus", "laststatus")))

How can I make it? The output should be:

 dat$firststatus = c(50.5,51, 51)
dat$laststatus = c(50.5,53,52)

Thanks in advance for your advice.

You could do:

cbind(dat, `colnames<-`(t(apply(dat, 1, function(x) {
  x <- grep("-", x);
  colnames(dat)[x[c(1, length(x))]]
  })), c("firststatus", "laststatus")))
#>      50   50.5 51   51.5 52   52.5 53   firststatus laststatus
#> 1001 "9"  "-8" NA   NA   NA   NA   NA   "50.5"      "50.5"    
#> 1002 NA   NA   "-3" NA   "3"  NA   "-4" "51"        "53"      
#> 1003 "11" "6"  "-7" NA   "-5" NA   NA   "51"        "52"

Created on 2022-05-28 by the reprex package (v2.0.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