tomw
tomw

Reputation: 3158

Using dplyr::rowwise to report which variable is the maximum, by row

I need a variable which reports which of five numeric variables is highest, separately by row.

Here's my data

library(tidyverse)

t1 <- tribble(
   ~v1,  ~v2,  ~v3,  ~v4,  ~v5,
  0.94, 0.96, 0.71, 0.14, 0.71,
  0.85,  0.6, 0.03, 0.52, 0.99,
  0.12, 0.83, 0.15, 0.84, 0.65,
  0.02, 0.48, 0.34, 0.98, 0.24,
  0.74, 0.16,  0.9, 0.63, 0.45
  )

My new variable, x1, will equal 2 for row 1, 5 for row 2, etc, indicating the location of the row maximum, for each row.

My attempt to use rowwise is unsuccessful

t1 %>% 
  rowwise %>% 
  mutate(
    x1 = which.max(.)
  )

returns

Error in `mutate()`:
ℹ In argument: `x1 = which.max(.)`.
ℹ In row 1.
Caused by error in `which.max()`:
! 'list' object cannot be coerced to type 'double'

Upvotes: 0

Views: 27

Answers (1)

langtang
langtang

Reputation: 24722

You can use which.max()

t1$x = apply(t1,1, which.max)

Output

# A tibble: 5 × 6
     v1    v2    v3    v4    v5     x
  <dbl> <dbl> <dbl> <dbl> <dbl> <int>
1  0.94  0.96  0.71  0.14  0.71     2
2  0.85  0.6   0.03  0.52  0.99     5
3  0.12  0.83  0.15  0.84  0.65     4
4  0.02  0.48  0.34  0.98  0.24     4
5  0.74  0.16  0.9   0.63  0.45     3

Alternatively, you can use this within a mutate statement, if you like:

mutate(t1, x=apply(t1,1,which.max))

Finally, you can also use rowwise():

rowwise(t1) %>% mutate(x = which.max(c_across()))

Upvotes: 1

Related Questions