Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge three different columns into a date in R

Tags:

r

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 
like image 394
viethaihp291 Avatar asked Oct 13 '14 07:10

viethaihp291


People also ask

How do I combine all columns into one column in R?

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)).

How do I combine columns from a different Dataframe in R?

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.

How do I combine three columns in R?

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.


2 Answers

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" 
like image 165
akrun Avatar answered Oct 28 '22 23:10

akrun


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)) 
like image 37
mtedwards Avatar answered Oct 29 '22 00:10

mtedwards