如何改变这个输入(顺序:时间,输入,输出,文件):
Time In Out Files
1 2 3 4
2 3 4 5
到这个输出(序列:时间,输出,输入,文件)?
Time Out In Files
1 3 2 4
2 4 3 5
这是虚拟R数据:
table <- data.frame(Time=c(1,2), In=c(2,3), Out=c(3,4), Files=c(4,5))
table
## Time In Out Files
##1 1 2 3 4
##2 2 3 4 5
Dplyr 1.0.0版本包含了relocate()函数来轻松地重新排序列:
dat <- data.frame(Time=c(1,2), In=c(2,3), Out=c(3,4), Files=c(4,5))
library(dplyr) # from version 1.0.0 only
dat %>%
relocate(Out, .before = In)
or
dat %>%
relocate(Out, .after = Time)
你的数据帧有四列,比如df[,c(1,2,3,4)]。
注意,第一个逗号表示保留所有行,1、2、3、4表示列。
要像上面的问题一样改变顺序,请执行df2[,c(1,3,2,4)]
如果你想以csv格式输出这个文件,请执行write.csv(df2, file="somedf.csv")
Dplyr有一个函数,允许您将特定列移动到其他列的前面或后面。当您使用大数据框架时,这是一个关键的工具(如果是4列,使用前面提到的select更快)。
https://dplyr.tidyverse.org/reference/relocate.html
在你的情况下,它将是:
df <- df %>% relocate(Out, .after = In)
简单而优雅。它还允许你一起移动几列,并将其移动到开始或结束:
df <- df %>% relocate(any_of(c('ColX', 'ColY', 'ColZ')), .after = last_col())
再次强调:当你使用大数据框架时,超级强大:)
一个dplyr解决方案(tidyverse包集的一部分)是使用select:
select(table, "Time", "Out", "In", "Files")
# or
select(table, Time, Out, In, Files)