1

Q1:

sorting = function (table, column) {
  # mtcars[order(mpg),]
  return(table[order(column),])
}

sorting(mtcars, "mpg") is equivalent to mtcars[order("mpg"),] but not equals to the result I want to get which is mtcars[order(mpg),], how can I convert it from string to column name.

Q2:

similar:

library(tidyr)
comb = function(table, colNNN, arr, sep) {
  return(unite(table, colNNN, all_of(arr), sep = sep))
}

and I do

comb(mtcars,"gearCarb",c("gear","carb"), "-")

and I got colNNN as the final column name,

so how to convert symbol into a String?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Please see [here](https://stackoverflow.com/questions/51501989/how-to-sort-data-by-column-in-descending-order-in-r) for information on Q1, I would recommend looking into using `table[[column]]` there. For #2, see [here](https://dplyr.tidyverse.org/articles/programming.html) for programming in the tidyverse and one of many [SO posts](https://stackoverflow.com/questions/57004055/programming-with-tidyeval-the-mutate-function-after-tidyrunitecol-col) on the topic, specifically on your exact question. – caldwellst Apr 02 '20 at 09:41

1 Answers1

0

Q1 can be solved without using non-standard evaluation using arrange_at from dplyr.

library(dplyr)
library(tidyr)
library(rlang)

sorting = function (table, column) {
   return(table %>% arrange_at(column))
}

sorting(mtcars, "mpg")

#    mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#1  10.4   8 472.0 205 2.93 5.250 17.98  0  0    3    4
#2  10.4   8 460.0 215 3.00 5.424 17.82  0  0    3    4
#3  13.3   8 350.0 245 3.73 3.840 15.41  0  0    3    4
#4  14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
#5  14.7   8 440.0 230 3.23 5.345 17.42  0  0    3    4
#6  15.0   8 301.0 335 3.54 3.570 14.60  0  1    5    8
#...

For Q2 we can use {{}}

comb = function(table, colNNN, arr, sep) {
  return(unite(table, {{colNNN}}, arr, sep = sep))
}

comb(mtcars,"gearCarb",c("gear","carb"), "-")

#                     mpg cyl  disp  hp drat    wt  qsec vs am gearCarb
#Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1      4-4
#Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1      4-4
#Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1      4-1
#Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0      3-1
#Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0      3-2
#Valiant             18.1   6 225.0 105 2.76 3.460 20.22  1  0      3-1
#...
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213