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.
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)
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(...))))
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.
© 2024 OneMinuteCode. All rights reserved.