Amgh
Amgh

Reputation: 21

R: match () only returns first occurrence

I have a dataframe

names2 <- c('AdagioBarber','AdagioBarber', 'Beethovan','Beethovan')
Value <- c(33,55,21,54)
song.data <- data.frame(names2,Value)

I would like to arrange it according to this character vector

names <- c('Beethovan','Beethovan','AdagioBarber','AdagioBarber')

I am using match() to achieve this

data.frame(song.data[match((names), (song.data$names2)),])

The problem is that match returns only first occurences

      names2            Value
3      Beethovan         21
3.1    Beethovan         21
1      AdagioBarber      33
1.1    AdagioBarber      33

Upvotes: 2

Views: 978

Answers (1)

Joe Shields
Joe Shields

Reputation: 113

You can use order, as @zx8754 and @Evan Friedland have pointed out.

> name.order <- c('Beethovan','AdagioBarber')           
> song.data$names2 <- factor(song.data$names2, levels= name.order)                                              
> song.data[order(song.data$names2), ]                                                                          
        names2 Value        
3    Beethovan    21        
4    Beethovan    54        
1 AdagioBarber    33        
2 AdagioBarber    55        

Basically, factor turns the strings into integers and creates a lookup table of what integers correspond to what strings. The levels argument specifies what you want that lookup table to be. Without that argument, it would just go by order of appearance.

So for example:

> as.numeric(factor(letters[1:5]))                                                                              
[1] 1 2 3 4 5               
> as.numeric(factor(letters[1:5], levels=c("d","b","e","a","c")))                                               
[1] 4 2 5 1 3  

Note: You'll need to be absolutely sure you get all your (correctly spelled) levels in that name.order vector, otherwise you'll end up with NA's in the output from order.

(I'm not sure why sort doesn't have the ability to sort factors, but it is what it is.)

Upvotes: 1

Related Questions