I want to max the data frame horizontally with R.

Asked 2 years ago, Updated 2 years ago, 107 views

There are columns from x_1 to x_17 in the R data frame. For each row, I would like to extract a column with the largest and largest values (extract 6 if x6 is the largest), dplyr::mutate, and add it to the new column.
I would appreciate it if you could let me know the details.

r tidyverse

2022-09-30 21:45

3 Answers

This is what tidyverse would look like.

library(tidyverse)
iris[-5]%>%
  mute(rn=row_number())%>%
  pivot_longer(-rn)%>%
  group_by(rn)%>%
  mute(
    max_idx = which.max(value),
    max_val = max(value)
  %>%
  ungroup()%>%
  pivot_wider(names_from=name, values_from=value)%>%
  select (-rn)


2022-09-30 21:45

You can also use purrr::pmap, base::pmax.

library(tidyverse)

# example data
set.seed(1)
N_COL<-17
N_ROW<-8
df_<-runif(N_ROW*N_COL)%>%
  round(2)%>%
  matrix(N_ROW,N_COL)%>%
  as.data.frame()%>%
  set_names(str_c("X_", seq_len(MAX_COL))))) 

# procedure
df_%>%
  mute(X_max=pmap(select(.,X_1:X_15), ~pmax(...))))


2022-09-30 21:45

http://www.datasciencemadesimple.com/row-wise-operation-r-using-dplyr/
According to

iris%>%
  rowwise()%>%mute(row_max=max(Sepal.Length: Petal.Width))

It seems that you can use , but there is a page that says that it is not recommended to use rawwise.
https://notchained.hatenablog.com/entry/2017/11/15/212117
In that case, as some of you answered, purrr seems to handle it.


2022-09-30 21:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.