Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R paste function in dplyr doesn't iterate as expected

Tags:

r

dplyr

paste

I'm confused about the way the paste() function is behaving. I have a dplyr table with the following columns:

Year    Month    DayofMonth
2001    May      21
2001    May      22
2001    June     9
2001    March    4

Which I'd like to combine into a single column called "Date". I figured I'd used the command:

df2 = mutate(df, Date = paste(c(Year, Month, DayofMonth), sep = "-",))

Unfortunately, this seems to concatenate every element in Year, then every element in Month, then every element in DayofMonth so the result looks something like this:

2001-2001-2001-2001 ... May-May-June-March ... 21-22-9-4

How should I modify my command so that the paste function iterates over each row individually?

P.S. This is part of a Data Camp course and as such I am running commands through whatever version of R they've got on their server.

like image 742
Slavatron Avatar asked Nov 04 '15 19:11

Slavatron


1 Answers

Currently you are concatenating all the columns together. Take c() out of your paste() call to paste them together element-by-element.

mutate(df, Date = paste(Year, Month, DayofMonth, sep = "-"))
#   Year Month DayofMonth         Date
# 1 2001   May         21  2001-May-21
# 2 2001   May         22  2001-May-22
# 3 2001  June          9  2001-June-9
# 4 2001 March          4 2001-March-4
like image 70
Rich Scriven Avatar answered Nov 15 '22 00:11

Rich Scriven