Helan.ge
Helan.ge

Reputation: 31

Writing a function that returns n largest values given a dataset and a variable

The function im trying to write

f <- function(x, variable.name, n) {
  order <- x[order(x$variable.name, decreasing = TRUE), ]
  head(order, n = n)
}

should return largest n values of variable.name from dataset x. But when running the function:

f(x=iris, variable.name="Sepal.Length", n = 5)

R returns the following error message:

Error in order(df$var.name, decreasing = TRUE) : 
argument 1 is not a vector

Can someone help me understand what is wrong with the function? The input of the function works as intended when not inside the function.

Upvotes: 0

Views: 77

Answers (1)

anhtr
anhtr

Reputation: 61

The problem is that you are trying to call x$variable.name where variable.name is a character string that you defined. I think it's not how $ work. Use [[ instead:

f <- function(x, variable.name, n) {
  order <- x[order(x[[variable.name]], decreasing = TRUE), ] 
  head(order, n = n) 
}

Output

f(x=iris, variable.name="Sepal.Length", n = 5)
    Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
132          7.9         3.8          6.4         2.0 virginica
118          7.7         3.8          6.7         2.2 virginica
119          7.7         2.6          6.9         2.3 virginica
123          7.7         2.8          6.7         2.0 virginica
136          7.7         3.0          6.1         2.3 virginica

Upvotes: 1

Related Questions