I have a bunch of columns spread throughout a DataFrame. Those columns have one thing in common, which is that their column names all contain "___" in them. How do I move all of these columns to the end of the DataFrame?
e.g. aaa___1, abc_2___2, xyzhw1___3 ... etc.
CodePudding user response:
We can use contains
to select specified columns
df <- data.frame(col1=c(3,4),a__2=c(1,2),col2=c(5,6))
df
col1 a__2 col2
1 3 1 5
2 4 2 6
cbind(select(df,-contains("__")),select(df,contains("__")))
col1 col2 a__2
1 3 5 1
2 4 6 2
CodePudding user response:
Using order
and grepl
dat[order(grepl("___", colnames(dat)))]
A B aaa___1 abc_2___2 xyzhw1___3
1 3 5 1 2 4
2 4 6 2 3 5
3 5 7 3 4 6
4 6 8 4 5 7
data
dat <- structure(list(aaa___1 = 1:4, abc_2___2 = 2:5, A = 3:6,
xyzhw1___3 = 4:7, B = 5:8), class = "data.frame", row.names = c(NA, -4L))