【问题标题】:Apply ceiling to dataframe while ignoring non-numeric values将上限应用于数据框,同时忽略非数字值
【发布时间】:2018-07-03 20:17:40
【问题描述】:

我有超过 50,000 个不同个体的不同状态的数据框。状态是整数、小数、NULL 和字符的混合。我想将ceiling() 函数应用于数据框,但只更改数值,同时保持其他所有内容相同。

structure(list(`11/1/2014` = c("0", "NULL", "NULL", "NULL", "NULL", 
    "NULL"), `12/1/2014` = c("0", "0", "0", "0", "0", "0"), `1/1/2015` = c("0", 
    "0", "0", "0", "S", "0"), `2/1/2015` = c("0", "0", "1.72", "0", 
    "S", "0")), row.names = c(NA, 6L), class = "data.frame")

【问题讨论】:

  • 所有三列都是character,所以这是一个空操作。能否提供实际数据?我建议您遵循reproducible examples 中的建议,也许使用dput(x)(但如果数据较大,则仅使用样本)。
  • 换种说法:在标准data.frame 中,您不能在单个列中包含数字、字母,甚至是特殊的NULL。一旦您在一列数字(整数或浮点数)中有一个字母,它将所有数字转换为字符串。将真正的NULL(不是"NULL" 的字符串)嵌入到框架的列中是非常困难的,尽管这当然是可能的(使用嵌套)。

标签: r dplyr time-series


【解决方案1】:

当您尝试将非数字值强制转换为数字时,它们将变为 NAs。所以你可以使用这样的函数:

ceil <- function(x) {
  x_num <- suppressWarnings(as.numeric(x))
  ifelse(!is.na(x_num),
         as.character(ceiling(x_num)),
         as.character(x))
}

transmute_all(yourdataframe, ceil)
#   11/1/2014 12/1/2014 1/1/2015 2/1/2015
# 1         0         0        0        0
# 2      NULL         0        0        0
# 3      NULL         0        0        2
# 4      NULL         0        0        0
# 5      NULL         0        S        S
# 6      NULL         0        0        0

【讨论】:

    猜你喜欢
    • 2018-11-12
    • 2018-07-23
    • 2018-03-13
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 2021-04-30
    • 2015-03-07
    相关资源
    最近更新 更多