0

I have a dataframe:

df <- data.frame(year = c(200501:200512))

and I want to split the column into two at the 4th number, so that my data frame look like this:

df_split <- data.frame(year = rep(c(2005)), month = c(01:12)). 
zx8754
  • 52,746
  • 12
  • 114
  • 209

2 Answers2

1

This is not so much a question about data frames, but about vectors in R in general. If your actual problem contains more nuances, then update your question or post a new question.

If your vector year is numerical (as asked) you can do simple maths:

year0 <- 200501:200512
year <- as.integer(year0 / 100) # examine the result of `year0 / 100` to see why I use `as.integer` at all and not `round`.
month <- year0 - year

Edit: As nicola pointed out, we can calculate it in other ways, with exact same result:

year <- year0 %/% 100
month <- year0 %% 100
MrGumble
  • 5,631
  • 1
  • 18
  • 33
  • 3
    Use the `%/%` operator for the integer division and the modulo `%%` operator to get the month. – nicola Jan 05 '21 at 12:40
0

Alternatively, tidyr version may be more compact

library(tidyr)
df %>% separate(year, into = c("yr", "mth"), sep = 4, convert = TRUE)
nyk
  • 670
  • 5
  • 11