Right now, I am having 3 separate columns as year, month, and day in a data file in R. How do I merge these three columns into just one column and make R understand that it is date?
Here is what it looks like right now.
year mon day gnp 1947 1 1 238.1 1947 4 1 241.5 1947 7 1 245.6 1947 10 1 255.6 1948 1 1 261.7 1948 4 1 268.7
To convert multiple columns into single column in an R data frame, we can use unlist function. For example, if we have data frame defined as df and contains four columns then the columns of df can be converted into a single by using data. frame(x=unlist(df)).
Method 1 : Using plyr package rbind. fill() method in R is an enhancement of the rbind() method in base R, is used to combine data frames with different columns. The column names are number may be different in the input data frames. Missing columns of the corresponding data frames are filled with NA.
First, we used the paste() function from base R. Using this function, we combined two and three columns, changed the separator from whitespaces to hyphen (“-”). Second, we used the str_() function to merge columns. Third, we used the unite() function.
Try:
df$date <- as.Date(with(df, paste(year, mon, day,sep="-")), "%Y-%m-%d") df$date #[1] "1947-01-01" "1947-04-01" "1947-07-01" "1947-10-01" "1948-01-01" #[6] "1948-04-01"
Since your year, month and day types are numerical the best function to use is the make_date function from the lubridate package. The tidyverse style solution is therefore
library(tidyverse) library(lubridate) data %>% mutate(date = make_date(year, month, day))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With