Reputation: 1112
I have two dataframes:df1 and df2
df1=read.table(text="group co
A 24952
A 56826865
A 56829677
B 10951
B 24200
B 48557215
B 49537767", header=T, stringsAsFactors=F)
df2=read.table(text="group n1 n2 n3 n4
A 29671 0 46373 0.02
B 51236 0 57911 0.1
A 56483059 121.37 56826203 178.28
B 48497604 164.98 48531024 164.98", header=T, stringsAsFactors=F)
I would like to merge column 2:5 in df2
to df1
by following conditions:
df1$group==df2$group & if df1$co < min(df2$n1)
in the same group, then merge column 2:5 of min(df2$n1)
row from df2
to the corresponding rows in df1
; if df1$co > max(df2$n3)
, then merge column 2:5 of max(df2$n1)
row from df2
to the corresponding rows in df1
.The result is expected as:
result=read.table(text="group co n1 n2 n3 n4
A 24952 29671 0 46373 0.02
A 56826865 56483059 121.37 56826203 178.28
A 56829677 56483059 121.37 56826203 178.28
B 10951 51236 0 57911 0.1
B 24200 51236 0 57911 0.1
B 48557215 48497604 164.98 48531024 164.98
B 49537767 48497604 164.98 48531024 164.98", header=T, stringsAsFactors=F)
Thanks for helps.
Upvotes: 0
Views: 193
Reputation: 346
Using dplyr
:
require(dplyr)
First, I modify the dataframe df2
to know which row is a min row and which is a max row:
df2 %<>% group_by(group) %>%
mutate(cond2 = ifelse(n1 == min(n1), "min", ifelse(n3 == max(n3), "max", NA))) %>%
ungroup
Then, I join the two dataframes and filter:
df1 %>% left_join(df2, by = "group") %>%
group_by(group, co) %>%
mutate(cond = ifelse(co < min(n1), "min", ifelse(co > max(n3), "max", NA))) %>%
ungroup %>%
filter(cond == cond2) %>%
select(-cond, -cond2)
Which gives the output:
Source: local data frame [7 x 6]
group co n1 n2 n3 n4
1 A 24952 29671 0.00 46373 0.02
2 A 56826865 56483059 121.37 56826203 178.28
3 A 56829677 56483059 121.37 56826203 178.28
4 B 10951 51236 0.00 57911 0.10
5 B 24200 51236 0.00 57911 0.10
6 B 48557215 48497604 164.98 48531024 164.98
7 B 49537767 48497604 164.98 48531024 164.98
Upvotes: 1