r-将具有Excel日期的列设置为文本格式



我正在尝试读取一个Excel文件,其中有一系列列名为日期格式,即

|ID|Jan-21|Feb-21|Mar-21|etc|

这些由Excel保存为数字,并由读取

df <- readxl::read_excel("filename", sheet = "tab")

作为

|ID|44197|44228|44256|etc|

我想把这些转换回日期格式,我已经尝试过这个

toDateString <- Vectorize(function(value) {
number = as.numeric(value)
if_else(!is.na(number) & number >= 44197 & number <= 44256)
return(value)
else
return(format(number, "%b-%y")))
})
df2 <- df %>% rename_if(isDate, funs(toDateString))

但新的数据帧保持不变。我已经在DateString中检查了逻辑,这是有效的。我认为这是因为函数正在向量化,因为我看到了以下警告。。。

Warning messages:
1: In if (!is.na(number) & number >= 44197 & number <= 44256) return(TRUE) else return(FALSE) :
the condition has length > 1 and only the first element will be used
2: In if (!is.na(number) & number >= 44197 & number <= 44256) return(TRUE) else return(FALSE) :
the condition has length > 1 and only the first element will be used

欢迎任何想法。。。

试试这个函数:

toDateString <- function(x) {
inds <- grepl('^\d+$', x)
x[inds] <- format(as.Date(as.numeric(x[inds]), origin = '1899-12-30'), '%b-%y')
x
}
df <- data.frame(ID = 1:3, '44197' = rnorm(3), check.names = FALSE)
names(df) <- toDateString(names(df))
df
#  ID Jan-21
#1  1   0.68
#2  2  -0.32
#3  3  -1.31

最新更新