1

I am trying to find a smooth way of creating a new data frame based on specific criteria of other data frames.

I currently have multiple data frames. Examples are as follows.

data frame A:                  data frame B:                 data frame B:
i      j     Distance          i      j     Distance          i      j     Distance
10    -10       1              5      -20      10             5     -10       4
5     -10       2              5      -10       2            20      -20      3
15     -5       5              15     -10       1

I then want to make a data frame containing all the data from data frame A, B & C where i = 5 and j = -10. Hence the final data frame will be:

i     j     Distance
5    -10        2
5    -10        2
5    -10        4

I will be wanting to create multiple data frames based on different values of i and j so anything that is easily adaptable would be great!

Thanks, Fiona

1 Answer 1

2

We place the datasets in a list and do the subsetting

library(tidyverse)
list(A, B, C) %>% 
           map_df(~ .x %>% 
                     filter(i==5, j== -10))

Or we rbind all the datasets together and use subset

subset(rbind(A, B, C), i ==5 & j == -10)

and with tidyverse, the way would be

bind_rows(A, B, C) %>%
            filter(i == 5, j == -10)
#  i   j Distance
#1 5 -10        2
#2 5 -10        2
#3 5 -10        4

data

A <- data.frame(i = c(10, 5, 15), j = c(-10, -10, -5), Distance = c(1, 2, 5))
B <- data.frame(i = c(5, 5, 15), j = c(-20, -10, -10), Distance = c(10, 2, 1))
C <- data.frame(i = c(5, 20), j = c(-10, -20), Distance = c(4, 3))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for multiple different ways to do this :) I've used the subset(rbind(A,B,C), i==5 & j ==-10) and it works a treat. Very simple piece of code, so thank you once again :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.