r:使用pmax函数忽略NA值

  • 本文关键字:NA 函数 使用 pmax r
  • 更新时间 :
  • 英文 :


我正在尝试创建一个新的列与3列的最大值。

数据示例:

date          skyc1 skyc2 skyc3 
1995-01-01    0     1     3
1995-01-02    1     null  null
1995-01-03    1     3     null

我想要得到:

date          skyc1 skyc2 skyc3 max
1995-01-01    0     1     3     3
1995-01-02    1     null  null  1
1995-01-03    1     3     null  3

我试着使用:

df$max <- pmax(df$skyc1,df$skyc2,df$skyc3)

但是我得到了这个:

date          skyc1 skyc2 skyc3 max
1995-01-01    0     1     3     3
1995-01-02    1     null  null  null
1995-01-03    1     3     null  null

是否可以将null视为0 ?我想过将null替换为0,但我的数据集中的值实际上是0…

感谢

pmax中有na.rm,由于值为null,因此在此之前我们需要将nullNAreplace设置为"null"是一个字符串,列将是characterfactor。因此,在pmax步骤

之前,我们还需要将type更改为type.convert
df[-1] <- replace(df[-1], df[-1] == "null", NA)
df <- type.convert(df, as.is = TRUE)
df$max <- pmax(df$skyc1, df$skyc2, df$skyc3, na.rm = TRUE)
df$max
#[1] 3 1 3

如果'skyc'有很多列,那么它也可以自动化

nm1 <- grep('^skyc\d+$', names(df), value = TRUE)
df$max <- do.call(pmax, c(df[nm1], na.rm = TRUE))

数据
df <-structure(list(date = c("1995-01-01", "1995-01-02", "1995-01-03"
), skyc1 = c(0L, 1L, 1L), skyc2 = c("1", "null", "3"), skyc3 = c("3", 
"null", "null")), class = "data.frame", row.names = c(NA, -3L
))

最新更新