[英]Merge two columns to a value range column in R
I have a data.frame that looks like this.我有一个看起来像这样的 data.frame。
dat1=data.frame(begin=c(1,100,50,1000), end=c(100,200,400,2000), functions=c("A","B","C","D"))
begin end functions
1 100 A
100 200 B
50 400 C
1000 2000 D
I would like to convert this data frame to value range data.frame to be able to map another single data point data.frame.我想将此数据框转换为值范围 data.frame 以便能够映射另一个单个数据点 data.frame。
range functions
1:100 A
100:200 B
50:400 C
1000:2000 D
This is my single point data.frame that I would like to map in the range.这是我想在范围内映射的单点 data.frame。
dat2=data.frame(position=c(20,80,200, 1200, 1500))
position
20
80
200
1200
1500
I want to generate a data.frame that looks like this.我想生成一个看起来像这样的 data.frame。 Not exactly like but at least to incorporate the Infos of the functions of each position.
不完全一样,但至少整合了每个职位的功能信息。
position function1 fucntion2
20 A
80 A C
200 B C
1200 D
1500 D
Thank you for your time.感谢您的时间。 Any help and direction are appreciated
任何帮助和方向表示赞赏
Does this get you the information you need?这是否可以为您提供所需的信息? You can then
pivot_wider()
or tweak it to however you want it formatted.然后,您可以
pivot_wider()
或将其调整为您想要的格式。
library(dplyr)
library(tidyr)
dat2 %>%
crossing(dat1) %>%
filter(position >= begin & position <= end)
# A tibble: 7 x 4
position begin end functions
<dbl> <dbl> <dbl> <chr>
1 20 1 100 A
2 80 1 100 A
3 80 50 400 C
4 200 50 400 C
5 200 100 200 B
6 1200 1000 2000 D
7 1500 1000 2000 D
Does this work:这是否有效:
> library(purrr)
> library(dplyr)
> dat1 %>% mutate(range = map2(begin, end, `:`)) %>% unnest(range) %>% right_join(dat2, by = c('range' = 'position'), keep = T) %>% select(-range)
# A tibble: 7 x 4
begin end functions position
<dbl> <dbl> <chr> <dbl>
1 1 100 A 20
2 1 100 A 80
3 100 200 B 200
4 50 400 C 80
5 50 400 C 200
6 1000 2000 D 1200
7 1000 2000 D 1500
>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.