一种在大数据帧中使用R对列重新排序的简便方法
这个问题与大型数据帧中列的重新排序有关,例如,大约有800列。数据框在每个id的不同日期之前有许多列名(即第一列)。类似的问题出现在网上(例如和),但它们的具体内容不适合我的情况。数据集的一个示例如下所示一种在大数据帧中使用R对列重新排序的简便方法,r,dataframe,R,Dataframe,这个问题与大型数据帧中列的重新排序有关,例如,大约有800列。数据框在每个id的不同日期之前有许多列名(即第一列)。类似的问题出现在网上(例如和),但它们的具体内容不适合我的情况。数据集的一个示例如下所示 df <- structure( list( id = c(1L, 2L, 3L, 4L,5L), date1 = c("1/4/2004", "3/8/2004", "NA", "13/10/2004","11/3/2003"), ax=c(1,2,1,"NA",5),
df <-
structure(
list(
id = c(1L, 2L, 3L, 4L,5L),
date1 = c("1/4/2004", "3/8/2004", "NA", "13/10/2004","11/3/2003"),
ax=c(1,2,1,"NA",5),
am=c(1,0,1,0,0),
aq=c(0,0,1,1,1),
date2 = c("8/6/2002", "11/5/2004", "3/5/2004",
"25/11/2004","21/1/2004"),
bx=c(3,2,6,1,5),
bm=c(1,1,0,1,1),
bq=c(1,0,1,0,0),
date3=c("23/6/2006", "24/12/2006", "18/2/2006", "NA","NA"),
cx=c(1,2,4,1,0),
cm=c(1,1,0,1,1),
cq=c(1,0,1,0,0)
),
.Names = c("id",
"date1","ax","am","aq","date2","bx","bm","bq","date3","cx","cm","cq"),
class = "data.frame",
row.names = c(NA,-5L)
)
然而,我正在寻找一个非常方便的代码,可以轻松地处理大数据。非常感谢您的帮助。如果您的完整数据符合您概述的模式,您可以循环使用位置调整向量,如下所示:
df[c(1, (2:ncol(df) + c(0,1,1,-2)))]
id date1 am aq ax date2 bm bq bx date3 cm cq cx
1 1 1/4/2004 1 0 1 8/6/2002 1 1 3 23/6/2006 1 1 1
2 2 3/8/2004 0 0 2 11/5/2004 1 0 2 24/12/2006 1 0 2
3 3 NA 1 1 1 3/5/2004 0 1 6 18/2/2006 0 1 4
4 4 13/10/2004 0 1 NA 25/11/2004 1 0 1 NA 1 0 1
5 5 11/3/2003 0 1 5 21/1/2004 1 0 5 NA 1 0 0
说明:
模式是保持日期不变,将第二列和第三列向前移动一列,将第四列向后移动两列。我们可以创建一个向量:
adj.pattern <- c(0,1,1,-2)
然后,我们使用此索引对数据帧进行排序(在ID列的开头添加1
):
如果您想固定
id
和date
列,并根据名称对其内部的其余列进行排序,我们可以这样做
#1:ncol(df)
all_cols <- seq_len(ncol(df))
#Get indices of fixed columns
fixed_columns <- c(1, grep("date", names(df)))
#Get the name of columns apart from fixed ones
cols <- names(df)[-fixed_columns]
#Sort and match them and update the new order in all_cols
all_cols[-fixed_columns] <- match(sort(cols), names(df))
df[all_cols]
# id date1 am aq ax date2 bm bq bx date3 cm cq cx
#1 1 1/4/2004 1 0 1 8/6/2002 1 1 3 23/6/2006 1 1 1
#2 2 3/8/2004 0 0 2 11/5/2004 1 0 2 24/12/2006 1 0 2
#3 3 NA 1 1 1 3/5/2004 0 1 6 18/2/2006 0 1 4
#4 4 13/10/2004 0 1 NA 25/11/2004 1 0 1 NA 1 0 1
#5 5 11/3/2003 0 1 5 21/1/2004 1 0 5 NA 1 0 0
#1:ncol(df)
对于上面的示例数据,您的代码运行良好。如果我得到了理解,我将能够扩展它来处理完整的数据。你能解释一下吗。谢谢大家!@特里查德-为您添加了一个解释。
adj.pattern <- c(0,1,1,-2)
col.index <- 2:ncol(df) + adj.pattern
col.index
[1] 2 4 5 3 6 8 9 7 10 12 13 11
df[c(1, col.index)]
#1:ncol(df)
all_cols <- seq_len(ncol(df))
#Get indices of fixed columns
fixed_columns <- c(1, grep("date", names(df)))
#Get the name of columns apart from fixed ones
cols <- names(df)[-fixed_columns]
#Sort and match them and update the new order in all_cols
all_cols[-fixed_columns] <- match(sort(cols), names(df))
df[all_cols]
# id date1 am aq ax date2 bm bq bx date3 cm cq cx
#1 1 1/4/2004 1 0 1 8/6/2002 1 1 3 23/6/2006 1 1 1
#2 2 3/8/2004 0 0 2 11/5/2004 1 0 2 24/12/2006 1 0 2
#3 3 NA 1 1 1 3/5/2004 0 1 6 18/2/2006 0 1 4
#4 4 13/10/2004 0 1 NA 25/11/2004 1 0 1 NA 1 0 1
#5 5 11/3/2003 0 1 5 21/1/2004 1 0 5 NA 1 0 0