user2350622
user2350622

Reputation: 77

avoiding loops on split strings in r

My current DATE variable has entries like "Wednesday 01/01/86" I am trying to split days from dates and put them separately into two variables. My current code works but it has loops and may not be very efficient when dealing with large data. Any thoughts on improvement?

result$DATE <- as.character(result$DATE) ## cast DATE into character

new_DATE <- strsplit(result$DATE, " ") ## split days from dates

## store days and dates separately into two new variables
for(i in 1:length(result$DATE)) {
result$GAMEDATE[i] <- new_DATE[[i]][2]
result$GAMEDOW[i] <- new_DATE[[i]][1]
}

Upvotes: 0

Views: 85

Answers (3)

James
James

Reputation: 66864

You can sapply though the output from strsplit, but you are better off just using the Date class:

(x <- as.Date(c("Wednesday 01/01/86","Friday 03/01/86"), "%A %d/%m/%y"))
[1] "1986-01-01" "1986-01-03"

You can then format to however you desire:

format(x,"%d/%m/%Y")
[1] "01/01/1986" "03/01/1986"

Both of these functions are vectorised and therefore will be fast.

Upvotes: 0

Jilber Urbina
Jilber Urbina

Reputation: 61214

Consider strsplit

> dates <- c("Wednesday 01/01/86", "Thursday 02/01/86", "Friday 03/01/86")
> do.call(rbind, strsplit(dates, " ") )
     [,1]        [,2]      
[1,] "Wednesday" "01/01/86"
[2,] "Thursday"  "02/01/86"
[3,] "Friday"    "03/01/86"

Upvotes: 1

TheComeOnMan
TheComeOnMan

Reputation: 12905

> library(stringr)
> str_split_fixed("Wednesday 01/01/86",' ',2)
     [,1]        [,2]      
[1,] "Wednesday" "01/01/86"

Upvotes: 0

Related Questions