Reputation: 5512
I have a dataframe with this kind of column data.
1906-02-20
1906-02-21
I want to create separate columns with years, months and days.
Intended output:
1906 02 20
1906 02 21
I have used things like strptime and lubridate before. But not able to figure this out.
Upvotes: 0
Views: 55
Reputation: 92292
Try the separate
function in the tidyr
package
library(tidyr)
separate(df, "V1", into = c("year", "month", "day"), sep = "-")
# year month day
# 1 1906 02 20
# 2 1906 02 21
Data
df <- read.table(text = "
1906-02-20
1906-02-21
")
Upvotes: 0
Reputation: 459
Look at this:
X <- data.frame()
X <- rbind(strsplit(x = "1906-02-20", split = "-")[[1]])
colnames(X) <- c("year", "month", "day")
Upvotes: 0
Reputation: 10167
format(as.Date('2014-12-31'),'%Y %m %d')
(obviously you want to replace as.Date('2014-12-31')
with your date vector).
format()
converts dates to stings given the format string provided. for the individual year, month and date values, you want:
myData$year <- format(as.Date('2014-12-31'),'%Y')
#> "2014"
myData$month <- format(as.Date('2014-12-31'),'%m')
#> "12"
myData$day <- format(as.Date('2014-12-31'),'%d')
#> "31"
I often refer to this page when I need to look up the meaning of the format strings.
Upvotes: 1