【发布时间】:2016-04-21 08:15:18
【问题描述】:
我对 R 完全陌生,我尝试在谷歌上搜索我的问题的代表性解决方案一段时间,但到目前为止还没有找到足够的答案,所以我希望在这里寻求帮助可以解决这个问题。
我应该合并两个不同大小的数据集(其他包括年度数据:df_f,和其他月度数据:df_m)。我应该将较小的 df_f 合并到较大的 df_m,以使 df_f 的行有条件地与 df_m 合并。
这是我的问题的描述性示例(带有一些非常基本的可重复数字):
第一个数据集
a <- c(1990)
b <- c(1980:1981)
c <- c(1994:1995)
aa <- rep("A", 1)
bb <- rep("B", 2)
cc <- rep("C", 2)
df1 <- data.frame(comp=factor(c(aa, bb, cc)))
df2 <- data.frame(year=factor(c(a, b, c)))
other.columns <- rep("other_columns", length(df1))
df_f <- cbind(df1, df2, other.columns ) # first dataset
第二个数据集
z <- c(10:12)
x <- c(7:12)
xx <- c(1:9)
v <- c(2:9)
w <- rep(1990, length(z))
e <- rep(1980, length(x))
ee <- rep (1981, length(xx))
r <- rep(1995, length(v))
t <- rep("A", length(z))
y <- rep("B", length(x) + length(xx))
u <- rep("C", length(v))
df3 <- data.frame(month=factor(c(z, x, xx, v)))
df4 <- data.frame(year=factor(c(w, e, ee, r)))
df5 <- data.frame(comp=factor(c(t, y, u)))
df_m <- cbind(df5, df4, df3) # second dataset
输出:
> df_m
comp year month
1 A 1990 10
2 A 1990 11
3 A 1990 12
4 B 1980 7
5 B 1980 8
6 B 1980 9
7 B 1980 10
8 B 1980 11
9 B 1980 12
10 B 1981 1
11 B 1981 2
12 B 1981 3
13 B 1981 4
14 B 1981 5
15 B 1981 6
16 B 1981 7
17 B 1981 8
18 B 1981 9
19 C 1995 2
20 C 1995 3
21 C 1995 4
22 C 1995 5
23 C 1995 6
24 C 1995 7
25 C 1995 8
26 C 1995 9
> df_f
comp year other.columns
1 A 1990 other_columns
2 B 1980 other_columns
3 B 1981 other_columns
4 C 1994 other_columns
5 C 1995 other_columns
我想根据条件 comp、year 和 month 将 df_f 中的行放置到 df_m(将 df_f 中的数据存储到 df_m 中的新列)。 Comp(公司)需要始终匹配,但匹配年份取决于月份:如果月份大于 6,则数据集之间匹配年份,如果月份小于 7,则年份 + 1(在 df_m 中)与年份(在 df_f )。注意,df_f中的某一行要根据条件放到df_m中的几行中。
想要的输出阐明了问题和目标:
想要的输出:
comp year month comp year other.columns
1 A 1990 10 A 1990 other_columns
2 A 1990 11 A 1990 other_columns
3 A 1990 12 A 1990 other_columns
4 B 1980 7 B 1980 other_columns
5 B 1980 8 B 1980 other_columns
6 B 1980 9 B 1980 other_columns
7 B 1980 10 B 1980 other_columns
8 B 1980 11 B 1980 other_columns
9 B 1980 12 B 1980 other_columns
10 B 1981 1 B 1980 other_columns
11 B 1981 2 B 1980 other_columns
12 B 1981 3 B 1980 other_columns
13 B 1981 4 B 1980 other_columns
14 B 1981 5 B 1980 other_columns
15 B 1981 6 B 1980 other_columns
16 B 1981 7 B 1981 other_columns
17 B 1981 8 B 1981 other_columns
18 B 1981 9 B 1981 other_columns
19 C 1995 2 C 1994 other_columns
20 C 1995 3 C 1994 other_columns
21 C 1995 4 C 1994 other_columns
22 C 1995 5 C 1994 other_columns
23 C 1995 6 C 1994 other_columns
24 C 1995 7 C 1995 other_columns
25 C 1995 8 C 1995 other_columns
26 C 1995 9 C 1995 other_columns
提前非常感谢您!我希望这个问题足够清楚,至少解释起来有点困难。
【问题讨论】:
-
@chris link 这会有所帮助
-
你能检查你的代码来创建
df_m吗,它会抛出错误 -
'df_m' 工作得很好,至少对我来说是这样
-
xxx没有在任何地方定义。 -
感谢@Stibu 的评论!我在那里的大纲有误。公司应始终匹配,正如您所说,当月份 >6 时应匹配年份,如果月份
标签: r merge conditional