Home > Software design >  Creating a matrix by splitting a vector
Creating a matrix by splitting a vector

Time:06-21

The string:

f <- c("20-04-2018","15-07-2021","11-11-2022","08-12-2021","28-01-2020")

Allocate one column for the day, month and year.

Anyone who knows what code to use to solve this question?

CodePudding user response:

One way:

> 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"
> 

Another, better, way using date functions:

> 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
> 

CodePudding user response:

Yet another way:

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"

CodePudding user response:

Base R using regex and strcapture():

as.matrix(
  strcapture(
    pattern = "^(\\d{2})\\-(\\d{2})\\-(\\d{4})$",
    x = f,
    proto = list(
      day = integer(), 
      month = integer(), 
      year = integer()
    )
  )
)

Base R option 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
)
  • Related