Предполагая, что столбцы обоих фреймов данных находятся в том же порядке, как описано, вы можете использовать функцию class
в подходе Map
.
df2[] <- Map(function(x, y) {
if (any(grepl("POS", y)))
ISOdate(as.Date(x), 0, 0, 0)
else if (y == "Date")
as.Date(x)
else
`class<-`(as.character(x), y)
}, df2, lapply(df1, class))
Демонстрация
До
lapply(df1, class)
# $name
# [1] "character"
#
# $date
# [1] "POSIXct" "POSIXt"
#
# $age
# [1] "numeric"
#
# $date2
# [1] "Date"
lapply(df2, class)
# $HEX
# [1] "factor"
#
# $date
# [1] "factor"
#
# $age
# [1] "factor"
#
# $date2
# [1] "factor"
Преобразование
df2[] <- Map(function(x, y) {
if (any(grepl("POS", y)))
ISOdate(as.Date(x), 0, 0, 0)
else if (y == "Date")
as.Date(x)
else
`class<-`(as.character(x), y)
}, df2, lapply(df1, class))
После
lapply(df2, class)
# $HEX
# [1] "character"
#
# $date
# [1] "POSIXct" "POSIXt"
#
# $age
# [1] "numeric"
#
# $date2
# [1] "Date"
Данные
df1 <- structure(list(name = c("A", "B", "C", "D", "E"), date = structure(c(1577836800,
1580515200, 1583020800, 1585699200, 1588291200), class = c("POSIXct",
"POSIXt")), age = c(30, 27, 25, 28, 23), date2 = structure(c(18262,
18293, 18322, 18353, 18383), class = "Date")), row.names = c(NA,
-5L), class = "data.frame")
df2 <- structure(list(HEX = structure(1:5, .Label = c("A", "B", "C",
"D", "E"), class = "factor"), date = structure(1:5, .Label = c("2020-01-01 01:00:00",
"2020-02-01 01:00:00", "2020-03-01 01:00:00", "2020-04-01 02:00:00",
"2020-05-01 02:00:00"), class = "factor"), age = structure(c(5L,
3L, 2L, 4L, 1L), .Label = c("23", "25", "27", "28", "30"), class = "factor"),
date2 = structure(1:5, .Label = c("2020-01-01", "2020-02-01",
"2020-03-01", "2020-04-01", "2020-05-01"), class = "factor")), row.names = c(NA,
-5L), class = "data.frame")