开发者

change columns position in a data frame using a tab txt list in R

开发者 https://www.devze.com 2023-04-10 14:06 出处:网络
Maybe this is a simple question, but I\'m trying to change the position of columns in a data frame in R. I\'ve got this data frame

Maybe this is a simple question, but I'm trying to change the position of columns in a data frame in R. I've got this data frame

TargetID   1065197   1005204     97610   1011789    101075   1002206
cg00000029 0.4192448 0.4177188 0.4797760 0.4214448 0.5500357 0.5535228
cg00000108 0.9191919 0.9358317 0.9428818 0.9397804 0.9293985 0.9495835
cg00000109 0.8935743 0.9157031 0.8731022 0.8734130 0.9226335 0.8980497
cg00000165 0.1387203 0.1699675 0.2031603 0.1683728 0.1822674 0.1623122
cg00000236 0.7502784 0.7324294 0.7895553 0.7096000 0.7878484 0.7747281
cg00000289 0.5698198 0.5864769 0.6527094 0.5058923 0.6033058 0.6524675

And I want to rearrange the positions using this tabulated text file, which indicates every pair of columns in order

101075 1005204
97610 1002206
1011789 1065197

So the result must be something like this

colnames(reordered_data_frame)
TargetID 101075 1005204 97610 1002206开发者_JAVA百科 1011789 1065197

Any ideas?


If you have a vector of column names in order, say:

colorder=c(101075, 1005204, 97610, 1002206,1011789 ,1065197)

You can re-order your columns using (assuming your dataframe is named dat):

newDf <- dat[, c("TargetID", colorder)]

Normally, you'd need to call as.character() on colorder (since the column names are numbers), but when we concatenate the "TargetID" text, the vector c("TargetID", colorder) is converted to character. In general, though, it isn't the best idea to use numerics as column names.


Read columns names from text file named "columns.txt

cols <- scan("columns.txt","character")

Rearrange data

redf <- dat[,c("TargetID",cols)]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号