1

Suppose we have a data frame

> (df <- as.data.frame(matrix(1:12, 3, 4)))
  V1 V2 V3 V4
1  1  4  7 10
2  2  5  8 11
3  3  6  9 12

Is there a way to let which() throw column numbers in an unordered form? I. e. which(names(df) %in% c("V1", "V4", "V3")) yielding 1, 4, 3 instead of 1, 3, 4? Or, if there isn't, how can we achieve this most easily?

10 Rep
  • 2,217
  • 7
  • 19
  • 33
jay.sf
  • 60,139
  • 8
  • 53
  • 110
  • would it be acceptable to randomise the values in the dataframe? there would be a solution with `sample` [link](https://stackoverflow.com/questions/6422273/how-to-randomize-or-permute-a-dataframe-rowwise-and-columnwise) – mischva11 Jul 27 '18 at 13:39
  • what are you trying to achieve (real world application)? And as 李哲源 says, why not `match(c("V1", "V4", "V3"), names(df))`? – s_baldur Jul 27 '18 at 13:41
  • 1
    Following @李哲源 `match(c("V1", "V4", "V3"), names(df))`. – Rui Barradas Jul 27 '18 at 13:43

1 Answers1

2

Following comments, we can use match()

> na.omit(match(c("V1", "V4", "V5"), names(df)))
[1] 1 4
attr(,"na.action")
[1] 3
attr(,"class")
[1] "omit"

Application at selection /organization of columns of a data frame (special case, when a match is NA):

> df[, na.omit(match(c("V1", "V4", "V3", "V999"), names(df)))]
  V1 V4 V3
1  1 10  7
2  2 11  8
3  3 12  9
jay.sf
  • 60,139
  • 8
  • 53
  • 110