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)).
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)).
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
Alternatively, tidyr
version may be more compact
library(tidyr)
df %>% separate(year, into = c("yr", "mth"), sep = 4, convert = TRUE)