简体   繁体   English

查找每行中第一个和最后一个负值的名称

[英]finding the colnames of first and last negative value in each row

I have a subset of data as below and I would like to add two columns where is gives me the colnames of first and last negative value in each row.我有一个如下的数据子集,我想添加两列,其中 is 给我每行中第一个和最后一个负值的列名。

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

I tried below, but it seems not true:我在下面尝试过,但似乎不正确:

dat$firststatus<- colnames(dat)[max.col(!is.na(dat<0), ties.method = "first")]
dat$laststatus<- colnames(dat)[max.col(!is.na(dat<0), ties.method = "last")]

thanks for your help.谢谢你的帮助。

Try this尝试这个

Data数据

df <- structure(list(`50` = c(NA, NA, 11), 
                     `50.5` = c(-8.01e-14, NA, 6),
                     `51` = c(NA, -3, -7), 
                     `51.5` = c(NA_real_, NA_real_, NA_real_),
                     `52` = c(NA, 3, -5.0015e-08), `52.5` = c(NA_real_, NA_real_,
                      NA_real_), `53` = c(NA, -4.5, NA)), class = "data.frame",
                      row.names = c(NA, -3L))
df

and add the required columns并添加所需的列

df$lastage <- sapply(1:nrow(df) ,
        \(x) rev(colnames(df))[which(rev(!is.na(df[x,])))][1])

df$firststatus <- sapply(1:nrow(df) ,
 \(x) colnames(df)[which(df[x,] < 0)][1])

df$laststatus <- sapply(1:nrow(df) ,
 \(x) rev(colnames(df))[which(rev(df[x,]) < 0)][1])

Output输出

50      50.5   51  51.5          52 52.5   53 firststatus
1 NA -8.01e-14 NA   NA          NA   NA   NA        50.5
2 NA        NA -3   NA  3.0000e+00   NA -4.5          51
3 11  6.00e+00 -7   NA -5.0015e-08   NA   NA          51
  laststatus
1       50.5
2         53
3         52

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

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