Question

I have a data frame with the following column names:

 [1] "416362" "417510" "402634" "406503" "417510" "402634" "402634" "402634" "402634" "402634" "406801" "416631" "407508" "413513" "406801" "416362" "416631" "406603" "407508" "416631" "406603" "406531" "402634" "402634" "402634"
[26] "406503" "413513" "416631" "416631" "406531"

Notice that the numbers are jumbled and that there are duplicates

I want to reorganize the columns so that they follow this order:

[1] "402634" "406503" "406531" "406603" "406801" "407508" "413513" "416362" "416631" "417510"

So I want all the column numbers that have "402634" in the jumbled matrix. Then all the column numbers that have "406503" in the jumbled matrix, in a vector, say "x".

I then want to go df[,x] to reorganize my data frame df.

Thanks!

Was it helpful?

Solution

Use the order command on the column names:

currentNames = c("416362","417510","402634","406503","417510","402634","402634","402634","402634","402634",
                 "406801","416631","407508","413513","406801","416362","416631","406603","407508","416631",
                 "406603","406531","402634","402634","402634","406503","413513","416631","416631","406531")
df = data.frame(matrix(nrow=3,ncol=length(currentNames)))
colnames(df) = currentNames
df[1:nrow(df),1:ncol(df)] = runif(nrow(df)*ncol(df))
df = df[,order(colnames(df),decreasing=F)]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top