Bin
Bin

Reputation: 221

separate according to the length of the variable

For example, I have a time data.

time <- c(516, 715, 1625)

The first 516 means 5:16

The last one 1625 means 16:25. The first 1 or 2 numbers represent hours while the last 2 numbers represent minutes.

I want to separate them into hours and minutes. How to separate a variable according to its length?

Upvotes: 2

Views: 72

Answers (3)

akrun
akrun

Reputation: 887108

In addition to the string methods, convert it to date time object and extract the 'hour' and 'min'

v1 <- strptime(sprintf("%04d", time), format = "%H%M")
v1$hour
#[1]  5  7 16
v1$min
#[1] 16 15 25

Upvotes: 2

Maurits Evers
Maurits Evers

Reputation: 50668

A tidyverse option using separate and a positive look-ahead pattern

library(tidyverse)
df %>% separate(time, c("hours", "minutes"), sep = "(?=\\d{2}$)")
#  hours minutes
#1     5      16
#2     7      15
#3    16      25

Explanation: sep = "(?=\\d{2}$)" translates to separate entries into two parts at the point where the following and last two characters are two digits.


Or a base R alternative using strsplit

t(sapply(strsplit(as.character(df$time), ""), function(x)
    as.numeric(rev(tapply(
        x,
        rev(rep(1:ceiling(length(x) / 2), each = 2, length.out = length(x))),
        FUN = function(x) paste0(x, collapse = ""))))))
#     [,1] [,2]
#[1,]    5   16
#[2,]    7   15
#[3,]   16   25

Sample data

df <- read.table(text =
    "time
516
715
1625
", header = T)

Upvotes: 4

Jon Spring
Jon Spring

Reputation: 66480

Another tidyverse option:

library(tidyverse)
df %>% mutate(hours   = str_sub(time, end = -3),
              minutes = str_sub(time, -2))

  time hours minutes
1  516     5      16
2  715     7      15
3 1625    16      25

Upvotes: 2

Related Questions