合并r中的列值时,如何选择较高(最大)的值



我有一个名为x8的数据帧,但我想将这两个Yield列合并为一个称为x的列;苹果";,我希望选择更高的产量(0.8(。我希望x列选择较高的值。

r代码:

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

Dput

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")

也许你在找这个?

#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

我们需要首先将列转换为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

或者另一个选项是matrixStats中的rowMaxs

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

最新更新