R - Using str_split and unlist to create two columns

j riot picture j riot · Jun 30, 2014 · Viewed 22.4k times · Source

I have a dataset that has dates and interest rates in the same column. I need to split these two numbers into two separate columns, however when I use the following code:

 Split <- str_split(df$Dates, "[ ]", n = 2)
 Dates <- unlist(Split)[1]
 Rates <- unlist(Split)[2]

It returns only the first "value" of each element, i.e., "1971-04-01" for Dates and "7.43" for Rates. I need it to return all values for the portion of the string split and the same for the second portion of the string split

Below is a portion of the dataset, total rows = 518.

    1971-04-01   7.31
    1971-05-01   7.43
    1971-06-01   7.53
    1971-07-01   7.60
    1971-08-01   7.70
    1971-09-01   7.69
    1971-10-01   7.63
    1971-11-01   7.55
    1971-12-01   7.48
    1972-01-01   7.44

Thanks

Answer

David Arenburg picture David Arenburg · Jun 30, 2014

Could do

Split <- strsplit(as.character(df$Dates), " ", fixed = TRUE)
Dates <- sapply(Split, "[", 1)
Rates <- sapply(Split, "[", 2)