user3787315
user3787315

Reputation: 65

Text process using R

I am quite new in programming and R Software.

My data-set includes date-time variables as following:

2007/11/0103
2007/11/0104
2007/11/0105
2007/11/0106

I need an operator which count from left up to the character number 10 and then execute a space and copy the last two characters and then add :00 for all columns.

Expected results:

2007/11/01 03:00
2007/11/01 04:00
2007/11/01 05:00
2007/11/01 06:00

Upvotes: 1

Views: 154

Answers (4)

David Arenburg
David Arenburg

Reputation: 92292

If you want to actually turn your data into a "POSIXlt" "POSIXt" class in R (so you could subtract/add days, minutes and etc from/to it) you could do

# Your data
temp <- c("2007/11/0103", "2007/11/0104", "2007/11/0105", "2007/11/0106")

temp2 <- strptime(temp, "%Y/%m/%d%H")
## [1] "2007-11-01 03:00:00 IST" "2007-11-01 04:00:00 IST" "2007-11-01 05:00:00 IST" "2007-11-01 06:00:00 IST"

You could then extract hours for example

temp2$hour
## [1] 3 4 5 6

Add hours

temp2 + 3600
## [1] "2007-11-01 04:00:00 IST" "2007-11-01 05:00:00 IST" "2007-11-01 06:00:00 IST" "2007-11-01 07:00:00 IST"

And so on. If you just want the format you mentioned in your question (which is just a character string), you can also do

format(strptime(temp, "%Y/%m/%d%H"), format = "%Y/%m/%d %H:%M")
#[1] "2007/11/01 03:00" "2007/11/01 04:00" "2007/11/01 05:00" "2007/11/01 06:00"

Upvotes: 6

akrun
akrun

Reputation: 887108

Try

library(lubridate)
dat <- read.table(text="2007/11/0103
2007/11/0104
2007/11/0105
2007/11/0106",header=F,stringsAsFactors=F)

dat$V1 <- format(ymd_h(dat$V1),"%Y/%m/%d %H:%M")
dat
#                 V1
#  1 2007/11/01 03:00
#  2 2007/11/01 04:00
#  3 2007/11/01 05:00
#  4 2007/11/01 06:00

Upvotes: 2

Davide Passaretti
Davide Passaretti

Reputation: 2771

Suppose your dates are a vector named dates

library(stringr)
paste0(paste(str_sub(dates, end=10), str_sub(dates, 11)), ":00")

Upvotes: 1

Joe
Joe

Reputation: 1535

paste and substr are your friends here. Type ? before either to see the documentation

my.parser <- function(a){
  paste0(substr(a, 0,10),' ',substr(a,11,12),':00') # paste0 is like paste but does not add whitespace
}

a<- '2007/11/0103'
my.parser(a) # = "2007/11/01 03:00"

Upvotes: 0

Related Questions