简体   繁体   English

如何使用 dplyr 在 R 中找到第一个值的列?

[英]How to find column with first of value in R using dplyr?

Consider the following example data:考虑以下示例数据:

d <- tibble(V1 = c(5, 3, 8, 7),
            V2 = c(4, 0, 2, 6),
            V3 = c(0, 1, 0, 3),
            V4 = c(0, 0, 0, 2))

# A tibble: 4 × 4
     V1    V2    V3    V4
  <dbl> <dbl> <dbl> <dbl>
1     5     4     0     0
2     3     0     1     0
3     8     2     0     0
4     7     6     3     2

I want to find the column name with the first 0 for each row.我想为每行找到第一个 0 的列名。 If there are no zeros, then I want to get the last column name.如果没有零,那么我想获取最后一个列名。

The result should look like this:结果应如下所示:

# A tibble: 4 × 5
     V1    V2    V3    V4 firstZero
  <dbl> <dbl> <dbl> <dbl> <chr>    
1     5     4     0     0 V3       
2     3     0     1     0 V2       
3     8     2     0     0 V3       
4     7     6     3     2 V4

max.col from base R is fast base R max.col max.col 很快

 d$firstZero <- ifelse(!rowSums(d == 0), names(d)[ncol(d)], 
   names(d)[max.col(d == 0, 'first')])

using dplyr使用dplyr

library(dplyr)
d %>% 
 rowwise %>% 
  mutate(firstZero = names(.)[match(0, c_across(everything()), 
       nomatch = ncol(.))]) %>% 
  ungroup

-output -输出

# A tibble: 4 × 5
     V1    V2    V3    V4 firstZero
  <dbl> <dbl> <dbl> <dbl> <chr>    
1     5     4     0     0 V3       
2     3     0     1     0 V2       
3     8     2     0     0 V3       
4     7     6     3     2 V4       

Or using case_when with max.col或者将case_whenmax.col一起使用

d %>% 
  mutate(firstZero = names(.)[case_when(!rowSums(across(c(V1, V2, V3)) == 0) ~ 
     ncol(.), TRUE ~  max.col(!across(c(V1, V2, V3)) != 0, "first"))])

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

相关问题 如何使用 R dplyr 找到行中第一个非零值的列索引? - How can I find the column index of the first non-zero value in a row with R dplyr? 如何使用 dplyr 找到每一行具有特定值的第一列 - How to find the first column with a certain value for each row with dplyr R:如何在第一列中查找值并在第三列中求和 - R: how to find value in first column and sum value of the third column 在使用 dplyr 的特定列值的第一个实例之后过滤 dataframe 中的 R 中的行 - Filter rows in dataframe in R after first instance of specific column value using dplyr “R:dplyr:如何添加一个将值除以第一组值的列(类似于vlookup)” - “R: dplyr: How to add a column that divides a value by the first group of values (kind of like a vlookup)” R:使用 dplyr 时如何找到比率 - R: how to find the ratio when using dplyr 使用dplyr仅在另一个值之后找到一个值的第一次出现 - Find first occurrence of a value only after another value using dplyr r、dplyr:如何使用 gsub 根据另一列中的值转换一列中的值 - r, dplyr: how to transform values in one column based on value in another column using gsub 使用dplyr mutate在组中查找第一次出现的值 - Find first occurence of value in group using dplyr mutate 如何使用dplyr根据组选择数据框列的第一个值? - How to select the first value of a column of a data frame according to the group using dplyr?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM