简体   繁体   English

如何在R中找到每行的第一个和最后一个负值的列名

[英]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".我想找到具有负值的第一行和最后一行的列名,并将其作为“firststatus”和“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)reprex 包于 2022-05-28 创建 (v2.0.1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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