字串:
f <- c("20-04-2018","15-07-2021","11-11-2022","08-12-2021","28-01-2020")
為日、月和年分配一列。
誰知道用什么代碼來解決這個問題?
uj5u.com熱心網友回復:
單程:
> f <-c("20-04-2018","15-07-2021","11-11-2022","08-12-2021","28-01-2020")
> do.call(rbind,strsplit(f, "-"))
[,1] [,2] [,3]
[1,] "20" "04" "2018"
[2,] "15" "07" "2021"
[3,] "11" "11" "2022"
[4,] "08" "12" "2021"
[5,] "28" "01" "2020"
>
使用日期函式的另一種更好的方法:
> D <- data.frame(date=as.Date(f, "%d-%m-%Y"))
> D$year <- as.integer(format(D$date, "%Y"))
> D$month <- as.integer(format(D$date, "%m"))
> D$day <- as.integer(format(D$date, "%d"))
> D
date year month day
1 2018-04-20 2018 4 20
2 2021-07-15 2021 7 15
3 2022-11-11 2022 11 11
4 2021-12-08 2021 12 8
5 2020-01-28 2020 1 28
>
uj5u.com熱心網友回復:
還有一種方式:
f |>
strsplit(split = "-") |>
unlist() |>
matrix(ncol = 3, byrow = TRUE)
[,1] [,2] [,3]
[1,] "20" "04" "2018"
[2,] "15" "07" "2021"
[3,] "11" "11" "2022"
[4,] "08" "12" "2021"
[5,] "28" "01" "2020"
uj5u.com熱心網友回復:
Base R 使用正則運算式和strcapture():
as.matrix(
strcapture(
pattern = "^(\\d{2})\\-(\\d{2})\\-(\\d{4})$",
x = f,
proto = list(
day = integer(),
month = integer(),
year = integer()
)
)
)
基礎 R 選項 2:
type.convert(
simplify2array(
within(
data.frame(f_date = as.Date(f, "%d-%m-%Y")),
{
day <- strftime(f_date, "%d")
month <- strftime(f_date, "%m")
year <- strftime(f_date, "%Y")
f_date <- NULL
}
),
higher = FALSE
),
as.is = TRUE
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/494177.html
上一篇:比較文本和字串Jquery
