Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

r - Finding rowwise minimum and column index in a tibble


I have the following tibble:

> df <- tibble(
     ID = LETTERS[1:4],
     a  = c(1,5,9,8),
     b  = c(5,9,8,2),
     c  = c(5,4,5,5)
)

> df
# A tibble: 4 x 4
  ID        a     b     c
  <chr> <dbl> <dbl> <dbl>
1 A         1     5     5
2 B         5     9     4
3 C         9     8     5
4 D         8     2     5
> 

What I want is to get the rowwise minimum of columns a:c and also the column index from this minimum.
The output tabel should look like this:

# A tibble: 4 x 6
  ID        a     b     c   Min Col_Index
  <chr> <dbl> <dbl> <dbl> <dbl>     <dbl>
1 A         1     5     5     1         1
2 B         5     9     4     4         3
3 C         9     8     5     5         3
4 D         8     2     5     2         2

I don't want to use rowwise()!

Thank you!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One option could be:

df %>%
 rowwise() %>%
 mutate(min = min(c_across(a:c)),
        min_index = which.min(c_across(a:c)))

  ID        a     b     c   min min_index
  <chr> <dbl> <dbl> <dbl> <dbl>     <int>
1 A         1     5     5     1         1
2 B         5     9     4     4         3
3 C         9     8     5     5         3
4 D         8     2     5     2         2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...