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))
但是新的数据框保持不变。我检查了 toDateString 中的逻辑并且有效。我认为这是因为该函数正在矢量化,因为我看到以下警告...
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
推荐阅读
- html - 从后端编辑 WordPress 页面
- javascript - JS select2插件在选项打开时不滚动
- node.js - 使用范围导入本地 npm 包
- c - 在 swift 5 中将 void* 参数传递给 c 函数时,不推荐使用“withUnsafeBytes”警告
- swift - 使用 takeSnapshot 的 WKWebView 的间歇性空白/部分屏幕截图
- opencv - 如何通过相机校准的结果计算以毫米为单位的焦距?
- javascript - 数组函数类型语法
- go - 总是从 POST req 得到空的身体
- wordpress - 元查询比较事件日期的问题
- javascript - jquery DataTable中按钮的onClick函数