Hugo Ehrstein
Hugo Ehrstein

Reputation: 69

Sort column names by number

I have 3 differents dataframes. After a colname(df) , i have this form of name column for a dataframe :

Name Length 20 21 22 23 24 25 26

Name Length factor 18 19 20 21 22 23 24

Name Length deep 18 19 20 21 22 23 24 25 26

But I would like to get the largest and smallest element (the numbers are always in the right order but not necessarily in the same position.)

in this example, it would be for the first: 20 , 26 for the second: 18 , 24 and for the third: 18 , 26

I use: range(colname(df), finite = TRUE)

but the results is "18" "length"

Any idea?

Upvotes: 0

Views: 256

Answers (1)

akrun
akrun

Reputation: 887711

We can convert the column names to numeric for the selected columns and then take the range

nm1 <- grep("^\\d+$", names(df1))
range(as.numeric(names(df1)[nm1]))

It can be converted to a function

f1 <- function(data) {

  nm1 <- grep("^\\d+$", names(data))
  range(as.numeric(names(data)[nm1]))
  }

f1(df1)
f1(df2)

It can also be directly converted without subsetting the column, but there will be a warning message

range(as.numeric(names(df1)), na.rm = TRUE)

Upvotes: 2

Related Questions