I want to sort my.data[4:10] in descending order by row. Some clues here, but I could not parse it sufficiently: Sort second to fifth column for each row in R.
I al
This answer's approach, which you quote above, is close:
cbind(df[,1], t(apply(df[,-1], 1, sort)))
but it needed two changes:
[,1]
and [,-1]
to [, 1:3]
and [, -(1:3)]
, respectively.sort
sorts in increasing order while you want decreasing order, and drops the NAs out entirely, while you want them last. You can fix this by adding the decreasing=TRUE, na.last=TRUE
arguments to sort
.This makes the solution:
cbind(my.data[, 1:3], t(apply(my.data[, -(1:3)], 1, function(v) sort(v, decreasing=TRUE, na.last=TRUE))))
Note that it might be a bit clearer if you split it onto multiple lines:
mysort = function(v) sort(v, decreasing=TRUE, na.last=TRUE)
sorted.cols = t(apply(my.data[, -(1:3)], 1, mysort))
cbind(my.data[, 1:3], sorted.cols)
This seems to work fine:
my.data[,4:10] <- t(apply(my.data[,4:10], 1, function(x) sort(x, na.last = T, decreasing=T)))
# habitat NumSites NumSamples Sp1 Sp2 Sp3 Sp4 Sp5 Sp6 Sp7
#1 Marsh 3 6 3 1 NA NA NA NA NA
#2 Prairie 3 5 2 2 2 NA NA NA NA
#3 Savanna 4 8 67 3 3 1 NA NA NA
#4 Swamp 1 2 2 NA NA NA NA NA NA
#5 Woodland 4 8 2 1 1 1 1 NA NA
You don't need an anonymous function on this.
> my.data[4:10] <-t(apply(my.data[4:10],1,sort,decreasing = TRUE,na.last = TRUE))
> my.data
# habitat NumSites NumSamples Sp1 Sp2 Sp3 Sp4 Sp5 Sp6 Sp7
# 1 Marsh 3 6 3 1 NA NA NA NA NA
# 2 Prairie 3 5 2 2 2 NA NA NA NA
# 3 Savanna 4 8 67 3 3 1 NA NA NA
# 4 Swamp 1 2 2 NA NA NA NA NA NA
# 5 Woodland 4 8 2 1 1 1 1 NA NA