R中数据帧中每行最大值的比率

我有一个与以下(df)相似的数据框。我需要添加一个新列,以指示每一行的最大值的比率(=行中的最大值除以该行中所有值的总和)。输出应类似于df1。

df <- data.frame('x' = c(1, 4, 1, 4, 1), 'y' = c(4, 6, 5, 2, 3), 'z' = c(5, 3, 2, 3, 2))

df1 <- data.frame('x' = c(1, 4, 1, 4, 1), 'y' = c(4, 6, 5, 2, 3), 'z' = c(5, 3, 2, 3, 2), 'ratio' = c(0.5, 0.462, 0.625, 0.444, 0.5)

谢谢!

评论
  • 十梦九你
    十梦九你 回复

    Here is a solution using dplyr:

    df %>% 
      rowwise() %>% 
      mutate(max_value = max(x,y,z),
             sum_values = sum(x,y,z),
             ratio = max_value / sum_values) #%>% 
      #select(-max_value, -sum_values) #uncomment this line if you want to df1 as in your question
    
    # A tibble: 5 x 6
          x     y     z max_value sum_values ratio
      <dbl> <dbl> <dbl>     <dbl>      <dbl> <dbl>
    1     1     4     5         5         10 0.5  
    2     4     6     3         6         13 0.462
    3     1     5     2         5          8 0.625
    4     4     2     3         4          9 0.444
    5     1     3     2         3          6 0.5 
    
  • 院子里画沙
    院子里画沙 回复
    library(tidyverse)
    df %>% 
      rowwise() %>% 
      mutate(MAX = max(x,y,z, na.rm = TRUE ),
             SUM = sum(x,y,z,  na.rm = TRUE),
             ratio = MAX / SUM)
    
    # A tibble: 5 x 6
          x     y     z   MAX   SUM ratio
      <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
    1     1     4     5     5    10 0.5  
    2     4     6     3     6    13 0.462
    3     1     5     2     5     8 0.625
    4     4     2     3     4     9 0.444
    5     1     3     2     3     6 0.5  
    
  • 小梨涡
    小梨涡 回复

    Another option with rowSums and pmax

    library(dplyr)
    library(purrr)
    df %>%
        mutate(ratio = reduce(., pmax)/rowSums(.))
    #  x y z     ratio
    #1 1 4 5 0.5000000
    #2 4 6 3 0.4615385
    #3 1 5 2 0.6250000
    #4 4 2 3 0.4444444
    #5 1 3 2 0.5000000
    

    Or in base R

    df$ratio <- do.call(pmax, df)/rowSums(df)