R使用dplyr将列移到最后 [英] R move column to last using dplyr
问题描述
对于具有 n 列的data.frame,我希望能够从 1-(n-1)位置中的任意位置移动一列第n列(即非最后一列成为最后一列)。我也想使用 dplyr
做到这一点。我想这样做不是简单地输入所有列的名称。
For a data.frame with n columns, I would like to be able to move a column from any of 1-(n-1) positions, to be the nth column (i.e. a non-last column to be the last column). I would also like to do it using dplyr
. I would like to do so without simply typing out the names of all the columns.
例如:
data<-data.frame(a=1:5, b=6:10, c=11:15)
这可行,但是不是 dplyr
的方式:
This works, but isn't the dplyr
way:
data[,c(colnames(data)[colnames(data)!='b'],'b')]
此是首先使列 b
的 dplyr
方法:
data%>%select(b, everything())
但这不能使列 b
最后:
data%>%select(everything(), b)
这可行,但是需要我输入所有列:
This works, but requires me to type out all the columns:
data%>%select(a,c,b)
那么有没有一种优雅的dplyr方法来做到这一点?
So is there an elegant dplyr way to do this?
相关问题:
- move column to first in a data frame
- How does one reorder columns in a data frame?
推荐答案
经过一番修补后,以下工作有效,几乎不需要键入。
After some tinkering, the following works and requires very little typing.
data%>%select(-b,b)
更新:dplyr 1.0.0
dplyr 1.0。 0
引入 relocate
动词:
data%> ;%relocate(b,.after = last_col())
我仍然更喜欢旧的 hacky方式。
I still prefer the old "hacky" way.
这篇关于R使用dplyr将列移到最后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!