Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...