I have a data.frame that looks like this.
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.
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.
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. 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.
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
>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.