簡體   English   中英

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

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

我想找到具有負值的第一行和最后一行的列名,並將其作為“firststatus”和“laststatus”兩列添加到數據框中。 這是一個例子:

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")))

我怎樣才能做到? 輸出應該是:

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

提前感謝您的建議。

你可以這樣做:

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"

reprex 包於 2022-05-28 創建 (v2.0.1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM