我有一个命名字符向量,我想按名称对其进行排序。微量元素:
# Character vector; assign names
vec <- letters[1:10]
names(vec) <- c(letters[20:11])
> vec
t s r q p o n m l k
"a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
# This does not work
> sort(vec)
t s r q p o n m l k
"a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
# Desired output
> vec
k l m n o p q r s t
"j" "i" "h" "g" "f" "e" "d" "c" "b" "a"
Run Code Online (Sandbox Code Playgroud)
sort的:namesvec
vec[sort(names(vec))]
# k l m n o p q r s t
#"j" "i" "h" "g" "f" "e" "d" "c" "b" "a"
Run Code Online (Sandbox Code Playgroud)
您还可以使用order:
vec[order(names(vec))]
Run Code Online (Sandbox Code Playgroud)