0

I have two data.frame, the first one is the date frame,the second one is the city frame ,and I am trying to merge the two frame into one.

the date frame:

date
2018/7/7
2018/7/8
2018/7/9

the city frame:

area
beijing
shanghai
guangzhou

The result I want is:

date             area
2018/7/7      beijing
2018/7/7      shanghai 
2018/7/7      guangzhou 
2018/7/8      beijing
2018/7/8      shanghai 
2018/7/8      guangzhou 
2018/7/9      beijing
2018/7/9      shanghai 
2018/7/9      guangzhou 

Thanks in advance!

beson_dong
  • 11
  • 1

3 Answers3

1

We can use expand.grid in base R

expand.grid(df1$date, df2$area)

Or crossing from tidyr

tidyr::crossing(df1, df2)

#   date     area     
#  <fct>    <fct>    
#1 2018/7/7 beijing  
#2 2018/7/7 guangzhou
#3 2018/7/7 shanghai 
#4 2018/7/8 beijing  
#5 2018/7/8 guangzhou
#6 2018/7/8 shanghai 
#7 2018/7/9 beijing  
#8 2018/7/9 guangzhou
#9 2018/7/9 shanghai 

data

df1 <- structure(list(date = structure(1:3, .Label = c("2018/7/7", "2018/7/8", 
"2018/7/9"), class = "factor")), class = "data.frame", row.names = c(NA, -3L))

df2 <- structure(list(area = structure(c(1L, 3L, 2L), .Label = c("beijing", 
"guangzhou", "shanghai"), class = "factor")), class = "data.frame", 
row.names = c(NA, -3L))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

This too can give you the output you want:

data.frame(date = sort(rep(df1$date, length(df2$area))), area= df2$area)
#       date      area
# 1 2018/7/7   beijing
# 2 2018/7/7  shanghai
# 3 2018/7/7 guangzhou
# 4 2018/7/8   beijing
# 5 2018/7/8  shanghai
# 6 2018/7/8 guangzhou
# 7 2018/7/9   beijing
# 8 2018/7/9  shanghai
# 9 2018/7/9 guangzhou
deepseefan
  • 3,701
  • 3
  • 18
  • 31
0

You can use lapply and rbind to make it when you are in base R

Reduce(rbind,lapply(df1$date, function(v) data.frame(date = v, area = df2["area"])))

where the output looks like:

      date      area
1 2018/7/7   beijing
2 2018/7/7  shanghai
3 2018/7/7 guangzhou
4 2018/7/8   beijing
5 2018/7/8  shanghai
6 2018/7/8 guangzhou
7 2018/7/9   beijing
8 2018/7/9  shanghai
9 2018/7/9 guangzhou
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81