我讀了一個 excel 檔案,其中包含一個包含日期和字串的死亡日期列。它在 excel 中看起來很好,但是當它被讀入 R 時,所有的日期都被轉換為 5 位數字 - 看起來像這樣:
#> date of death
#> <chr>
#> 1 44673
#> 2 44674
#> 3 alive
#> 4 not known
#> 5 NA
有沒有辦法
- 我可以以一種不會轉換為 5 位數字的方式讀取 excel 檔案嗎?
- 如果 1 不可能,有沒有辦法將該列轉換為日期,但僅限數字?
uj5u.com熱心網友回復:
如果我們想保持字串原樣,那么我們可以Date在讀取數字元素后轉換為類,然后coalesce使用原始列。請注意,列只能有一種型別,因此我們可能需要回傳character型別,因為有字串
library(dplyr)
df1 <- df1 %>%
mutate(`date of death` = coalesce(as.character(janitor::excel_numeric_to_date(
as.numeric(`date of death`))), `date of death`))
-輸出
df1
# A tibble: 6 × 2
`date of death` col2
<chr> <dbl>
1 2022-04-22 5
2 2022-04-23 3
3 alive 9
4 not known 10
5 NA 11
嘗試使用read.xlsx(from openxlsx) 和read_excel(from readxl)。根據創建的示例,在指定 時read_excel確實轉換為Date類col_types,但這也將導致NA同一列中的其他字串值。但是read.xlsx,detectDates轉換
library(openxlsx)
df1 <- read.xlsx(file.choose(), detectDates = TRUE)
df1
date.of.death col2
1 2022-04-22 5
2 2022-04-23 3
3 alive 9
4 not known 10
5 <NA> 11
> sapply(df1, class)
date.of.death col2
"character" "numeric"
check.names為了在列名中保留空格,我們可能需要指定sep.names
df1 <- read.xlsx(file.choose(), detectDates = TRUE,
check.names = FALSE, sep.names = " ")
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/494370.html
