简体   繁体   中英

Find and extract dataframe rows with matching attributes in r

I have a dataframe in r where each row is a record of the abundance of some animal species for a given time in a given place. I want to pull out all the pairwise sets of records with matching criteria of some kind. Example data here: http://tinyurl.com/qeqxx25

For each pair of rows that have the same values for WDPAID, Sp, and Method (eg, Record.Number 8 & 9), I would like to return a single record with the values for each column for each pair of records. For example, for Record.Numbers 8 & 9, I would like: http://tinyurl.com/nl3jn5b

Any pushes in the right direction are appreciated.

I would do that by merging the table to itself. Something among those lines

  ## Getting and preparing data
  >>df=data.frame(Record = c(8,9), WDPAID = c(1, 1), Year= c(2005, 2006), Method=c("a","a"))
  >>df$ind= 1:nrow(df)
  >>df2= df
  >> df
          Record WDPAID Year Method ind
    1      8      1 2005      a   1
    2      9      1 2006      a   2

## doing the merge 
 >> df_noisy = merge(df, df2, by.x = c("Method", "WDPAID") , by.y = c("Method","WDPAID"), suffixes=c(1,2))
 >> df_needed = df_noisy[df_noisy$ind1 != df_noisy$ind2, ]

Initial data set

   >> df_needed
         Method WDPAID Record1 Year1 ind1 Record2 Year2 ind2
2         a      1       8     2005    1       9   2006    2
3         a      1       9     2006    2       8   2005    1

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM