I'm having a bit of trouble trying to figure out how to rearrange rows in a data frame in R. According to the documentation, this can be done with the factor command, but this doesn't appear to be working. Here is a data frame called uCSE. When I try to reorder the levels of Comp, the order doesn't change (ie, the rows are still sorted alphabetically with Multi at the top).
> uCSE$Comp <- factor(uCSE$Comp, levels=c("No","Single","Multi"))
> uCSE
Source: local data frame [12 x 5]
Groups: Comp
Comp SNR meanCSE stdCSE SE
1 Multi 1 0.01522042 0.002184382 9.970293e-05
Any help would be greatly appreciated. Thanks!
Try wrapping the factor() with sort().
> a <- c("No", "single", "No", "Multi", "single", "No")
> a
[1] "No" "single" "No" "Multi" "single" "No"
> a.sorted <- sort(factor(a, levels=c("No", "single", "Multi")))
> a.sorted
[1] No No No single single Multi
Levels: No single Multi
The sort will work in the order you set the levels. Here I use different order of levels
> a.sorted2 <- sort(factor(a, levels=c("single", "Multi", "No")))
> a.sorted2
[1] single single Multi No No No
Levels: single Multi No
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.