如何将两个不同数据帧的两列按行绑定?

时间:2019-03-20 05:39:32

标签: r dataframe rbind

#--------Get Sunday's from 2018-01-01 till today---------------------
d = seq(as.Date("2018-01-01"),Sys.Date(),by='day')
sundayList = d[weekdays(d)=='Sunday']
HolidayList = as.data.frame(sundayList)
colnames(HolidayList)[1] = "Holidays"

#---------Get Alternate saturdays 2nd and 4th------------------------
d = seq(as.Date("2018-01-01"),Sys.Date(),by='day')
saturdayList = d[weekdays(d)=='Saturday']
altSaturdayList = lapply(split(saturdayList, format(saturdayList, "%Y-%m")), function(x)
  na.omit(x[c(2,4)]))
altSaturdayList = as.data.frame(altSaturdayList)
altSaturdayList = gather(altSaturdayList)
altSaturdayList = subset(altSaturdayList,select = c(colnames(altSaturdayList)[2]))

直到这里它按预期方式工作,但我无法将两列绑定为仅在一个数据帧中包含星期天以及第二个和第四个星期六

HolidayList$Holidays = rbind(HolidayList$Holidays,altSaturdayList$value)

任何改进现有代码的评论都会有所帮助。

我收到以下错误消息。

> HolidayList$Holidays = rbind(HolidayList$Holidays,altSaturdayList$value)
Error in `$<-.data.frame`(`*tmp*`, Holidays, value = c(17538, 17544, 17545,  : 
  replacement has 2 rows, data has 63
In addition: Warning message:
In rbind(HolidayList$Holidays, altSaturdayList$value) :
  number of columns of result is not a multiple of vector length (arg 2)

1 个答案:

答案 0 :(得分:1)

在列名相同后我们可以使用bind_rows

library(dplyr)
bind_rows(HolidayList, set_names(altSaturdayList, "Holidays"))

或与rbind

rbind(HolidayList, setNames(altSaturdayList, "Holidays"))