【问题标题】:When merging column values in r, How do you choose the higher (maximum) value合并r中的列值时,如何选择更高(最大值)的值
【发布时间】:2021-03-18 03:21:16
【问题描述】:

我有一个名为 x8 的数据框,但我想将两个 Yield 列合并到一个名为 x 的列中。对于“苹果”,我希望选择更高的产量(0.8)。我希望 x 列选择更高的值。

r 代码:

x8$x <- paste((x8[,2]),(x8[,4]))

输入

x8:

structure(list(Row.names = c("AAPL", "FB", "HRUB", "HUKX", "TSLA", 
"XLYS"), `12m yield` = c("0.8", "", "5.85", "4.19", "", "0.00"), 
    `Price to forecast PE` = c("", "", "7.92", "14.39", "", "23.16"
    ), Yield = c("0.7", "", "", "", "", ""), PE = c("37.3", "43.3", 
    "", "", "", ""), x = c(" 0.7", " ", "5.85 ", "4.19 ", " ", 
    "0.00 ")), row.names = c(NA, -6L), class = "data.frame")

【问题讨论】:

    标签: r dataframe merge max multiple-columns


    【解决方案1】:

    也许你在找这个?

    #Code
    x8$x <- apply(x8[,c(2,4)],1,max,na.rm=T)
    

    另外,如果你转换成数字,你会得到这个:

    #Code
    x8$`12m yield` <- as.numeric(x8$`12m yield`)
    x8$Yield <- as.numeric(x8$Yield)
    x8$x <- apply(x8[,c(2,4)],1,max,na.rm=T)
    

    输出:

    x8
      Row.names 12m yield Price to forecast PE Yield   PE    x
    1      AAPL      0.80                        0.7 37.3 0.80
    2        FB        NA                         NA 43.3 -Inf
    3      HRUB      5.85                 7.92    NA      5.85
    4      HUKX      4.19                14.39    NA      4.19
    5      TSLA        NA                         NA      -Inf
    6      XLYS      0.00                23.16    NA      0.00
    

    【讨论】:

      【解决方案2】:

      我们需要先将列转换为numeric,因为它们是character

      nm1 <- c("12m yield", "Yield")
      x8[nm1] <- lapply(x8[nm1], as.numeric)
      

      然后,使用pmax 得到max,即vectorized

      x8$x <- with(x8, pmax(`12m yield`, Yield, na.rm = TRUE))
      x8$x
      #[1] 0.80   NA 5.85 4.19   NA 0.00
      

      或者另一个选项是来自matrixStatsrowMaxs

      library(matrixStats)
      rowMaxs(as.matrix(x8[nm1]), na.rm = TRUE)
      #[1] 0.80 -Inf 5.85 4.19 -Inf 0.00
      

      或者使用tidyverse

      library(dplyr)
      x8 %>% 
           type.convert(as.is = TRUE) %>% 
           mutate(x = pmax(`12m yield`, Yield, na.rm = TRUE))
      #  Row.names 12m yield Price to forecast PE Yield   PE    x
      #1      AAPL      0.80                   NA   0.7 37.3 0.80
      #2        FB        NA                   NA    NA 43.3   NA
      #3      HRUB      5.85                 7.92    NA   NA 5.85
      #4      HUKX      4.19                14.39    NA   NA 4.19
      #5      TSLA        NA                   NA    NA   NA   NA
      #6      XLYS      0.00                23.16    NA   NA 0.00
      

      【讨论】:

        猜你喜欢
        • 2020-03-23
        • 2012-08-17
        • 1970-01-01
        • 2014-09-15
        • 1970-01-01
        • 2017-09-17
        • 2013-05-09
        • 2020-01-12
        • 2011-01-27
        相关资源
        最近更新 更多