R 根据不同dfs的列名为列指定固定顺序
我有多个数据帧,所有数据帧都包含一个或多个列(狗、猫、鸟或鱼)。对于所有的数据帧,我希望列的顺序是鱼、猫、狗、鸟R 根据不同dfs的列名为列指定固定顺序,r,dataframe,R,Dataframe,我有多个数据帧,所有数据帧都包含一个或多个列(狗、猫、鸟或鱼)。对于所有的数据帧,我希望列的顺序是鱼、猫、狗、鸟 df <- data.frame(dogs = c(1:2), cats = c(33:34), birds = c(2:3), fish = c(7:8)) dogs cats birds fish 1 1 33 2 7 2 2 34 3 8 df2 <- data.frame(dogs = c(5:6), cats
df <- data.frame(dogs = c(1:2), cats = c(33:34), birds = c(2:3), fish = c(7:8))
dogs cats birds fish
1 1 33 2 7
2 2 34 3 8
df2 <- data.frame(dogs = c(5:6), cats = c(103:104), birds = c(4:5))
dogs cats birds
1 5 103 4
2 6 104 5
现在我正在手动更改所有数据帧的列顺序(
df[,c(4,2,1,3)]
等),似乎找不到其他方法来解决这个问题。有什么建议吗?提前谢谢 在base R
中更容易的选项是match
要获取索引,请指定nomatch=0
,这样如果有不匹配的列,它就不会变为NA
。这里,我们创建一个用于多个数据集的函数
f1 <- function(dat, names_ord) {
dat[match(names_ord, names(dat), nomatch = 0)]
}
nm1 <- c('fish', 'cats', 'dogs', 'birds')
f1(df2, nm1)
# cats dogs birds
#1 103 5 4
#2 104 6 5
f1(df, nm1)
# fish cats dogs birds
#1 7 33 1 2
#2 8 34 2 3
一个
dplyr
选项可以是:
df %>%
select(any_of(c("fish", "cats", "dogs", "birds")))
fish cats dogs birds
1 7 33 1 2
2 8 34 2 3
df2 %>%
select(any_of(c("fish", "cats", "dogs", "birds")))
cats dogs birds
1 103 5 4
2 104 6 5
如果您有许多这样的数据集,那么通过添加purr
,您可以执行以下操作:
map(.x = list(df, df2),
~ .x %>%
select(any_of(c("fish", "cats", "dogs", "birds"))))
[[1]]
fish cats dogs birds
1 7 33 1 2
2 8 34 2 3
[[2]]
cats dogs birds
1 103 5 4
2 104 6 5
也许你可以试试
match
+na。像下面这样省略
> nmord <- c("fish", "cats", "dogs", "birds")
> df[na.omit(match(nmord, names(df)))]
fish cats dogs birds
1 7 33 1 2
2 8 34 2 3
> df2[na.omit(match(nmord, names(df2)))]
cats dogs birds
1 103 5 4
2 104 6 5
>nmord-df[na.omit(match(nmord,names(df)))]
鱼猫狗鸟
1 7 33 1 2
2 8 34 2 3
>df2[na.omit(匹配(nmord,名称(df2)))]
猫狗鸟
1 103 5 4
2 104 6 5
map(.x = list(df, df2),
~ .x %>%
select(any_of(c("fish", "cats", "dogs", "birds"))))
[[1]]
fish cats dogs birds
1 7 33 1 2
2 8 34 2 3
[[2]]
cats dogs birds
1 103 5 4
2 104 6 5
> nmord <- c("fish", "cats", "dogs", "birds")
> df[na.omit(match(nmord, names(df)))]
fish cats dogs birds
1 7 33 1 2
2 8 34 2 3
> df2[na.omit(match(nmord, names(df2)))]
cats dogs birds
1 103 5 4
2 104 6 5