Ciao, 这是我的可复制示例。
#this is the dataset i have
d <- c(1,2,3,4)
e <- c(7,4,6, NA)
f <- c(9,4,3,6)
g <- c(10,5,4,7)
mydata <- data.frame(d,e,f,g)
names(mydata) <- c("ID","scoreA","scoreB", "scoreC")
#this is the list that i want the columns to be in order by
target <- list("scoreB", "scoreC", "scoreA")
#this is the dataset i want
mydata1 <- data.frame(d,f,g,e)
names(mydata1) <- c("ID","scoreB","scoreC", "scoreA")
我在这里尝试了许多方法,但无法对此进行排序。例如我尝试过
mydata1 <- mydata[,target]
我知道这是不正确的,但我真的被困在这里。谢谢你。
答案 0 :(得分:1)
您可以使用dplyr
库非常直观地执行这种操作。 Here您可以找到更多。您还可以使用data.table
库(here是链接)。
library(dplyr)
# if you just want to select "target" columns in order
mydata %>%
select(ID, target)
# or you can specify column names in the select function
mydata %>%
select(ID, scoreB, scoreC, scoreA)
ID scoreB scoreC scoreA
1 1 9 10 7
2 2 4 5 4
3 3 3 4 6
4 4 6 7 NA
# if you want to select and then arrange (sort) data according to order
mydata %>%
select(ID, scoreB, scoreC, scoreA) %>%
arrange(scoreB, scoreC, scoreA)
ID scoreB scoreC scoreA
1 3 3 4 6
2 2 4 5 4
3 4 6 7 NA
4 1 9 10 7
# if you wanto to sort in descending order
mydata %>%
select(ID, scoreB, scoreC, scoreA) %>%
arrange(desc(scoreB, scoreC, scoreA))
ID scoreB scoreC scoreA
1 1 9 10 7
2 4 6 7 NA
3 2 4 5 4
4 3 3 4 6