Leaving the date column I would like to convert rest of the columns in a data frame from chr to numeric. How could I achieve this? There are many columns in the data frame and below is only an extract. Thanks.
Date RECORD Battery_V Data_logger_Temp_C VWC_CS7
2021-06-25 12:34:00 0 12.47 14.14 0.127
CodePudding user response:
Suppose we have the data frame shown reproducibly in the Note at the end. Then convert all columns except the first as shown. No packages are used.
DF2 <- replace(DF, -1, lapply(DF[-1], as.numeric))
or
DF2 <- DF
DF2[-1] <- lapply(DF2[-1], as.numeric)
or we can convert all character columns using:
ok <- sapply(DF, is.character)
DF2 <- replace(DF, ok, lapply(DF[ok], as.numeric))
or
DF2 <- DF
ok <- sapply(DF2, is.character)
DF2[ok] <- lapply(DF2[ok], as.numeric)
Note
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")
CodePudding user response:
library(dplyr)
df <- df %>%
mutate(across(.cols = -Date, as.numeric))