Christian Lura
Christian Lura

Reputation: 1

Extract and sort specific values from an R data frame

I´m quite new to R, and this might there be an easy answer to, but still: I have a data frame on the form

df <- data.frame(c("a", "b", "c", "d", "e"), 1:5, 7:11, stringsAsFactors=FALSE)
names(df) <- c("en", "to", "tre")

My dataset is way bigger than this, lots more rows and columns. But the basic idea is the same: I want to sort the n highest numeric values, independent of which column they appear in, and return a list with the values in decreasing order and their corresponding string in column "en".

Like this:

e  11
d  10
c   9
b   8
a   7
e   5

and so on.

How could I go about accomplishing this?

Upvotes: 0

Views: 1154

Answers (2)

dickoa
dickoa

Reputation: 18437

You can use the package reshape2 to melt your data and sort the value column, like this :

require(reshape2)
df <- data.frame(c("a", "b", "c", "d", "e"), 1:5, 7:11, stringsAsFactors=FALSE)
names(df) <- c("en", "to", "tre")

df2 <- melt(df, id = "en")
## 'data.frame':    10 obs. of  3 variables:
##  $ en      : chr  "a" "b" "c" "d" ...
##  $ variable: Factor w/ 2 levels "to","tre": 1 1 1 1 1 2 2 2 2 2
##  $ value   : int  1 2 3 4 5 7 8 9 10 11

df2[order(df2$value, decreasing = TRUE), c("en", "value")]
##    en value
## 10  e    11
## 9   d    10
## 8   c     9
## 7   b     8
## 6   a     7
## 5   e     5
## 4   d     4
## 3   c     3
## 2   b     2
## 1   a     1

But I'm sure there are other ways to do that !!

Upvotes: 3

Federico Giorgi
Federico Giorgi

Reputation: 10735

Less elegant but without extra packages (it will work with any number of columns):

col1<-rep(df[,1],ncol(df)-1)
col2<-c()
for(i in 2:ncol(df)) {
    col2<-c(col2,df[,i])
}
newdf<-data.frame(en=col1,value=col2)
newdf<-newdf[order(as.numeric(newdf[,2]),decreasing=TRUE),]

Upvotes: 0

Related Questions