将列移到数据框中的第一位置

将列移到数据框中的第一位置

本文介绍了将列移到数据框中的第一位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将数据帧的最后一列移到开头(作为第一列)。

I would like to have the last column of the data frame moved to the start (as first column). How can I do it in R?

我的data.frame有大约一千列可以更改顺序。我只想选择一个列并将其移至开头。

My data.frame has about a thousand columns to changing the order wont to. I just want to pick one column and "move it to the start".

推荐答案

我不知道是否值得添加这可以作为答案,也可以发表评论,但是我编写了一个名为 moveme 的函数,该函数可以让您使用所描述的语言进行操作。您可以在以下答案中找到该功能:

I don't know if it's worth adding this as an answer or if a comment would be fine, but I wrote a function called moveme that lets you do what you want to do with the language you describe. You can find the function at this answer: https://stackoverflow.com/a/18540144/1270695

它适用于 data.frame 名称,并产生一个可以用来重新排列列的字符向量:

It works on the names of your data.frame and produces a character vector that you can use to reorder your columns:

mydf <- data.frame(matrix(1:12, ncol = 4))
mydf
moveme(names(mydf), "X4 first")
# [1] "X4" "X1" "X2" "X3"
moveme(names(mydf), "X4 first; X1 last")
# [1] "X4" "X2" "X3" "X1"

mydf[moveme(names(mydf), "X4 first")]
#   X4 X1 X2 X3
# 1 10  1  4  7
# 2 11  2  5  8
# 3 12  3  6  9






如果您要像这样洗牌,建议您 data.frame data.table 并使用 setcolorder (如果需要,可以使用我的 moveme 函数)进行引用更改。


If you're shuffling things around like this, I suggest converting your data.frame to a data.table and using setcolorder (with my moveme function, if you wish) to make the change by reference.

在你里面问题中,您还提到我只想选择一列并将其移到开头。如果是任意列,而不是最后一列,则还可以使用 setdiff

In your question, you also mentioned "I just want to pick one column and move it to the start". If it's an arbitrary column, and not specifically the last one, you could also look at using setdiff.

想象您正在使用 mtcars数据集,并希望将 am列移到开头。

Imagine you're working with the "mtcars" dataset and want to move the "am" column to the start.

x <- "am"
mtcars[c(x, setdiff(names(mtcars), x))]

这篇关于将列移到数据框中的第一位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 02:47