Question: subsetting (querying) dataframe preserving order in R


subsetting (querying) dataframe preserving order in R

Answers 2
Added at 2016-12-21 16:12

I would like to know a way of subsetting with [] which preserves the order of the queries (authors), ex:

authors<-c("Almeda","Acosta", "Moscone", "Guerra")

authorcountry <- read.table(text="
 authoralone countryalone
1      Acosta     Argentina
2    Aguilera     Argentina
3      Almeda         U.S.A
4       Alves        Brazil
5      Araújo        Brazil
6 Bernardello     Argentina
7      Daviña     Argentina
8      Guerra        Brazil
9       Honfi     Argentina
10    Moscone     Argentina",header=TRUE,fill=TRUE,stringsAsFactors=FALSE)

authorcountry$countryalone[(authorcountry$authoralone %in% authors)]
#order should be:
#  [1] "U.S.A"     "Argentina" "Argentina" "Brazil"   

#as in:
get_merge<-merge(authors,authorcountry, by.x="authors", by.y="authoralone", sort = FALSE)
Answers to

subsetting (querying) dataframe preserving order in R

nr: #1 dodano: 2016-12-21 16:12

You can use match, i.e.

authorcountry$countryalone[match(authors, authorcountry$authoralone)]
#[1] "U.S.A"     "Argentina" "Argentina" "Brazil" 
nr: #2 dodano: 2016-12-21 16:12

Or using dplyr

authorcountry %>% 
        slice(match(authors, authoralone)) %>%
#[1] "U.S.A"     "Argentina" "Argentina" "Brazil"   
Source Show
◀ Wstecz