0

I have a very wide data.frame in R. In order to make it easier to read, I'd like the variables in a certain order. ID NAME GENDER EVERYTHING ELSE (ordered by alpha)

The below works, but seems clunky and I need something that can generalize ( i have more than 3 columns i need to set at the beginning). Is there an easier way to accomplish this or am I stuck doing it this way?

# Columns
A <- c(100, 200, 100)
name <- c("Tim", "Jim", "Kim")
C <- c(2, 2, 1)
ID <- c(110, 111, 112)
B <- c(300, 330, 320)
gender = c("M", "M", "F")
# Data.frame
have <- data.frame(A, name, C, ID, B, gender)
# Alpha
want <- have[, order(names(have))]
# Move columns
want <- want[,c(which(colnames(want)=="gender"), which(colnames(want)!="gender"))]
want <- want[,c(which(colnames(want)=="name"), which(colnames(want)!="name"))]
want <- want[,c(which(colnames(want)=="id"), which(colnames(want)!="id"))]
M--
  • 25,431
  • 8
  • 61
  • 93
pyll
  • 1,688
  • 1
  • 26
  • 44
  • Hope this link will help https://stackoverflow.com/questions/3369959/moving-columns-within-a-data-frame-without-retyping/18540144#18540144 – BENY Jun 08 '17 at 19:08
  • `df[,c("id",setdiff(names(df),"id"))]` – M-- Jun 08 '17 at 19:09

1 Answers1

1

You can easily do it like this (assuming you already sorted it):

mycol <- c("ID","name","gender")
want <-  want[,c(mycol,setdiff(names(want),mycol))]  

As I said, It can be done as simple as that but I missed using for in R:

mycol <- c("gender","name","ID") #in the reverse order that you want the first columns

for (i in 1:3){
    want <-  want[,c(mycol[i],setdiff(names(want),mycol[i]))]   
}

Result would be:

> (want)

#    ID name gender   A   B C 
# 1 110  Tim      M 100 300 2 
# 2 111  Jim      M 200 330 2 
# 3 112  Kim      F 100 320 1
M--
  • 25,431
  • 8
  • 61
  • 93