改进 R 中的 Max 函数

我有一个这样的数据框:

Df <- data.frame(A=c(2,3,9,12,2,5,7,1,23,4,14,8,6,11,4),B=c(1,2))

我的代码是:

   #translates the column based on the counter in column B
Df %>%
  mutate(B = if_else(B == 1,"A","B")) %>% 
  group_by(B) %>% 
  mutate(var = paste0("V",row_number())) %>% 
  pivot_wider(id_cols = B,names_from = var,values_from = A) %>% 
  rename(row_name = B)

#creates a new data frame
new <- Df %>%
  group_by(B) %>% 
  mutate(var = paste0("V",values_from = A)

#extraction of the maximum value and saving in a new df
new$row_maximum = apply(new[,-1],max)
complete <- new %>% rowwise() %>% mutate(Pos = which(c_across(V1:V10) == row_maximum )[1])

fin <- matrix(sample(c(0:0),50,replace = TRUE),nrow(complete))
fin <- as.data.frame(fin)

#part to improve
tab_max <- new$row_maximum
tab_max <- as.data.frame(tab_max)
fin$V14 <- tab_max

我的问题是:有没有办法改进最后一部分?是否可以使用保存在 complete$Pos 中的位置进行最后一步?

surveyphilylyp 回答:改进 R 中的 Max 函数

你可以尝试这样的事情:

library(dplyr)

fin <- Df %>%
  mutate(B = if_else(B == 1,"A","B")) %>% 
  group_by(B) %>% 
  summarise(var = "tab_max",max_val = max(A)) %>% 
  select(B,var,max_val) %>% 
  bind_rows(data.frame(B = rep(c("A","B"),25),var=rep(paste0("V",1:25),2),max_val = 0)) %>% 
  pivot_wider(names_from=var,values_from=max_val) %>% 
  select(paste0("V",1:13),tab_max,paste0("V",15:25)) %>% 
  as.data.frame()

哪个返回

  V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 tab_max V15 V16 V17 V18 V19 V20 V21 V22 V23 V24 V25
1  0  0  0  0  0  0  0  0  0   0   0   0   0      23   0   0   0   0   0   0   0   0   0   0   0
2  0  0  0  0  0  0  0  0  0   0   0   0   0      14   0   0   0   0   0   0   0   0   0   0   0
本文链接:https://www.f2er.com/36547.html

大家都在问