【问题标题】:Retain one column in a data frame as POSIXct and convert others to numeric in r将数据框中的一列保留为 POSIXct 并将其他列转换为 r 中的数字
【发布时间】:2021-12-29 18:35:15
【问题描述】:

离开日期列我想将数据框中的其余列从 chr 转换为数字。我怎么能做到这一点?数据框中有很多列,下面只是一个摘录。谢谢。

                 Date RECORD Battery_V Data_logger_Temp_C VWC_CS7
  2021-06-25 12:34:00      0     12.47              14.14   0.127

【问题讨论】:

  • 到目前为止有什么尝试?你知道colnames(df) 和例如for (col in colnames(df)) { # do something here ... } 吗?
  • 我在 sapply 上试了一下,但没有给出想要的输出。

标签: r dplyr data-transform


【解决方案1】:

假设我们在最后的注释中以可重复的方式显示了数据框。然后转换除第一列之外的所有列,如图所示。没有使用任何包。

DF2 <- replace(DF, -1, lapply(DF[-1], as.numeric))

DF2 <- DF
DF2[-1] <- lapply(DF2[-1], as.numeric)

或者我们可以使用以下方法转换所有字符列:

ok <- sapply(DF, is.character)
DF2 <- replace(DF, ok, lapply(DF[ok], as.numeric))

DF2 <- DF
ok <- sapply(DF2, is.character)
DF2[ok] <- lapply(DF2[ok], as.numeric)

注意

Lines <- "                 Date RECORD Battery_V Data_logger_Temp_C VWC_CS7
  2021-06-25T12:34:00      0     12.47              14.14   0.127"
DF <- read.table(text = Lines, header = TRUE, colClasses = "character",
  strip.white = TRUE)
DF$Date <- as.POSIXct(DF$Date, format = "%Y-%m-%dT%H:%M:%S")

【讨论】:

    【解决方案2】:
    library(dplyr)
    df <- df %>% 
      mutate(across(.cols = -Date, as.numeric))
    

    【讨论】:

    • 谢谢,虽然无法测试。
    猜你喜欢
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 2023-02-25
    • 2019-01-24
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多