Home > database >  how do I create a dataframe based on values from another dataframe?
how do I create a dataframe based on values from another dataframe?

Time:12-15

i have a data frame, from this I created another dataframe,
which consists of a selection after a number of conditions. The result is a number of countries that satisfy the condition n > 11. Now I want to continue working with only these countries. How can I copy values from the first dataset based on the countries in the selection?

My first df looks like:

enter image description here

and the second (so the selection of countries):

enter image description here

In my final df I need every column and row from my 1st df (but only for the countries present in the second df)

CodePudding user response:

I'm not sure about your data and reason using second dataframe, but let first and second data as df1 and df2, then

library(dplyr)

df1 %>%
  filter(Country.o... %in% df2$Country.o...)

(I cannot find out what is the column name. You should not post your data as an imange)

CodePudding user response:

Two options -

  1. Do an inner join

    a) Base R -

df3 <- merge(df1, df2, by = 'Country')

b) dplyr -

library(dplyr)
df3 <- inner_join(df1, df2, by = 'Country')
  1. Instead of creating df2 from df1, I would just filter the 1st one to get the resulting dataframe.
df3 <- df1 %>% group_by(Country) %>% filter(n() > 11)
  • Related