我正在尝试绑定两个不同长度的数据帧。
Category = c("New", "New","New","New","Old","Old","Old","Old",
"Expired", "Expired", "Expired", "Expired")
Monthly_Dates= c ('Jan-2014', 'Feb-2014', 'Mar-2014', 'Apr-2014',
'May-2014', 'Jun-2014', 'Jul-2014', 'Aug-2014', 'Sep-2014','Oct-2014','Nov-2014','Dec-2014')
Monthly_Vals = c(4,7,6,7,8,12,10,11,10,16,12,120)
monthly_df <- data.frame(Category, Monthly_Dates,Monthly_Vals)
Category = c("New","Old", "Expired", "Expired")
Quarterly_Date= c ( 'Mar-2014', 'Jun-2014', 'Sep-2014', 'Dec-2014')
Quarterly_Vals = c(4,7,6,7)
quarterly_df <- data.frame(Category, Quarterly_Date,Quarterly_Vals)
monthly_df = cbind(monthly_df, matrix(data = NA, ncol = ncol(monthly_df),
nrow = nrow(quarterly_df) - nrow(monthly_df),dimnames = list(NULL, names(monthly_df))));
Combined_dfs <- data.frame(monthly_df, quarterly_df)
View (Combined_dfs)
当我尝试
cbind
每月和每季度的值时,它会抛出错误,我做错了什么?
错误
Error in matrix(data = NA, ncol = ncol(monthly_df), nrow = nrow(quarterly_df) - :
invalid 'nrow' value (< 0)
预期结果
Category Monthly_Dates Monthly_Vals Quarterly_Date Quarterly_Vals
1 New Jan-2014 4 Mar-2014 4
2 New Feb-2014 7 Jun-2014 7
3 New Mar-2014 6 Sep-2014 6
4 New Apr-2014 7 Dec-2014 7
5 Old May-2014 8
6 Old Jun-2014 12
7 Old Jul-2014 10
8 Old Aug-2014 11
9 Expired Sep-2014 10
10 Expired Oct-2014 16
11 Expired Nov-2014 12
12 Expired Dec-2014 120
你可以做这样的事情,但我几乎不愿意建议它,因为我觉得它仍然避免了潜在的问题......
library(tidyverse)
monthly_df <- monthly_df %>% mutate(Row = row_number())
quarterly_df <- quarterly_df %>% mutate(Row = row_number())
monthly_df %>% full_join(quarterly_df, by = "Row")
Category.x Monthly_Dates Monthly_Vals Row Category.y Quarterly_Date Quarterly_Vals
1 New Jan-2014 4 1 New Mar-2014 4
2 New Feb-2014 7 2 Old Jun-2014 7
3 New Mar-2014 6 3 Expired Sep-2014 6
4 New Apr-2014 7 4 Expired Dec-2014 7
5 Old May-2014 8 5 <NA> <NA> NA
6 Old Jun-2014 12 6 <NA> <NA> NA
7 Old Jul-2014 10 7 <NA> <NA> NA
8 Old Aug-2014 11 8 <NA> <NA> NA
9 Expired Sep-2014 10 9 <NA> <NA> NA
10 Expired Oct-2014 16 10 <NA> <NA> NA
11 Expired Nov-2014 12 11 <NA> <NA> NA
12 Expired Dec-2014 120 12 <NA> <NA> NA
注意
Category
列的“重复”,因为它们出现在两个数据框中,并且您似乎不想加入它们。我向每个数据帧引入一个 Row
列,以便较短 df 的行绑定到较长 df 的相应行。
如果您只想要
Category
中的 monthly_df
,请在 quarterly_df
ing 之前将其从 join
中删除。