我有两个数据矩阵。
[2 0]
我想要的是将[2 1]
中的列名与set.seed(1)
df<-matrix(sample(1:1000, 20),nrow=4)
colnames(df)<-c("V1","V2","V3","V4","V5")
> df
V1 V2 V3 V4 V5
[1,] 266 201 625 679 707
[2,] 372 894 62 380 976
[3,] 572 940 204 760 374
[4,] 906 657 175 491 763
loc<-c("V1","V3","V5","V4","V2",
"V2","V4","V5","V3","V1",
"V5","V1","V2","V4","V3",
"V5","V3","V1","V2","V4")
中的列名进行比较,并按照df
中的指示重定位loc
中的值
我期望得到的结果应该像
df
任何帮助将不胜感激。谢谢!
答案 0 :(得分:4)
可以选择使用sapply
从loc
的每一行中获取相应的列(基于df
)。
m <- matrix(loc, byrow = TRUE, nrow = nrow(df))
result <- t(sapply(1:nrow(df), function(x)df[x,m[x,]]))
colnames(result) <- NULL
result
# [,1] [,2] [,3] [,4] [,5]
# [1,] 266 625 707 679 201
# [2,] 894 380 976 62 372
# [3,] 374 572 940 760 204
# [4,] 763 175 906 657 491
答案 1 :(得分:0)
您也可以这样做:
indices <- cbind( rep(1:nrow(df), each=ncol(df)), as.numeric(gsub("\\D", "", loc)) )
matrix(df[indices], nrow(df), byrow = TRUE)
# [,1] [,2] [,3] [,4] [,5]
#[1,] 266 625 707 679 201
#[2,] 894 380 976 62 372
#[3,] 374 572 940 760 204
#[4,] 763 175 906 657 491