Error in select unused arguments

This tutorial explains how to fix the following error you may encounter when using the dplyr package: error in select unused arguments.

One error you may encounter in R is:

Error in select(., cyl, mpg) : unused arguments (cyl, mpg) 

This error occurs when you attempt to use the select() function from the dplyr package in R but also have the MASS package loaded.

When this occurs, R attempts to use the select() function from the MASS package instead and an error is produced.

This tutorial shares exactly how to fix this error.

How to Reproduce the Error

Suppose we attempt to run the following code to summarize a variable in the mtcars dataset in R:

library(dplyr)
library(MASS)

#find average mpg grouped by 'cyl'
mtcars %>%
  select(cyl, mpg) %>%
  group_by(cyl) %>%
  summarize(avg_mpg = mean(mpg))

Error in select(., cyl, mpg) : unused arguments (cyl, mpg)

An error occurs because the select() function from the MASS package clashes with the select() function from the dplyr package.

How to Fix the Error

The easiest way to fix this error is to explicitly tell R to use the select() function from the dplyr package by using the following code:

library(dplyr)
library(MASS)

#find average mpg grouped by 'cyl'
mtcars %>%
  dplyr::select(cyl, mpg) %>%
  group_by(cyl) %>%
  summarize(avg_mpg = mean(mpg))

# A tibble: 3 x 2
    cyl avg_mpg
1     4    26.7
2     6    19.7
3     8    15.1

The code successfully runs because dplyr::select explicitly tells R to use the select() function from the dplyr package instead of the MASS package.

Additional Resources

The following tutorials explain how to troubleshoot other common errors in R:

How to Fix in R: names do not match previous names
How to Fix in R: longer object length is not a multiple of shorter object length
How to Fix in R: contrasts can be applied only to factors with 2 or more levels

The line of code below from the dplyr package is super simple. And yet, its giving me an error. I’m just trying to practice using the package and want to select a single column, cyl, from the data frame mtcars. What’s going on here? Any ideas?

> select(mtcars, cyl)

Error in select(mtcars, cyl) : unused argument (cyl)

Ronak Shah's user avatar

Ronak Shah

368k19 gold badges144 silver badges201 bronze badges

asked Jan 9, 2018 at 4:26

Mitsugi's user avatar

4

Came across the same error. Could not figure out what it was. Out of desperation I installed dplyr again and suddenly it worked…

answered Aug 14, 2018 at 20:21

Cul's user avatar

CulCul

511 silver badge2 bronze badges

I was having the same issue. It came out that i have not imported dplyr before calling the select method.

answered Apr 17, 2018 at 4:14

Som Dubey's user avatar

Som DubeySom Dubey

1011 silver badge6 bronze badges

2

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    In this article, we will be looking toward the approach to fix the error in selecting unused arguments in the R programming language.

    Error in selecting unused arguments: The R compiler produces this error when a programmer tries to use the select() function of the dplyr package in R provided that the MASS package loaded. R tries to make use of the select() function from the MASS package instead when such an error takes place. This article focuses on how to fix this error.

    Error: Error in select(., cyl, mpg) : unused arguments (cyl, mpg) 

    When the error might occur:

    Consider the following R program.

    Example:

    R

    library(dplyr)

    library(MASS)

    mtcars %>% select(cyl, mpg) %>% group_by(cyl) %>% summarize(avg_mpg = mean(mpg))

    Output:

    Interpretation: The compiler produces this error because there is a clash between the select() function from the MASS package and the select() function from the dplyr package.

    How to Fix the Error:

    This error can be eliminated by using the select() function directly from the dplyr package. 

    Example:

    R

    library(dplyr)

    library(MASS)

    mtcars %>%

      dplyr::select(cyl, mpg) %>%

      group_by(cyl) %>%

      summarize(avg_mpg = mean(mpg))

    Output:

    Interpretation: The code compiled successfully without any error because dplyr explicitly uses the select() function in the dplyr package rather than the MASS package.

    The “unused argument error in r” error message is primarily a coding mistake, a fact that makes it easy to find and correct. It results from incorrect entry of arguments into a function. It usually results from an easy-to-make mistake and one that is just as easy to correct. It can result from something as simple as hitting the wrong key. In most cases, once you find the mistake fixing the problem is easy.

    The circumstances of this error.

    The “unused argument error in r” message occurs when you are using a function in R. It occurs when an argument used does not match the arguments in the argument list. This is particularly true when a different argument is added than what is in the list. It does not occur just because an argument without a default argument value is missing because this causes a different message than a missing default value error.

    # r error unused argument
    > log(x=8)
    [1] 2.079442
    > log(x=8,y=7)
    Error in log(x = 8, y = 7) : unused argument (y = 7)

    It can happen with both built-in and user-defined functions. In both cases, this message occurs when a select unused argument is included in a function’s input. Anytime you include an unused argument in calling an r function you will get this error message.

    What is causing this problem?

    The “unused argument error in r” message is caused by a mistake in the code when entering an argument or object such as a data frame, vector, or matrix into a base r function. It is not a case of missing values or data but rather a variable that is not expected as an additional argument. It is easiest to illustrate this problem by using a user-defined r function argument.

    # unused argument error in r
    > expn = function(x,n)
    + {
    + xx = 1
    + for (i in 1:n) xx = xx*x
    + xx
    + }
    > expn(x = 4,n =3)
    [1] 64
    > expn(x = 4,n =3,s = 5 )
    Error in expn(x = 4, n = 3, s = 5) : unused argument (s = 5)
    > expn(x = 4,s = 5 )
    Error in expn(x = 4, s = 5) : unused argument (s = 5)

    In this example, the function definition raises “x” to the power of “n” to get the result as long as you enter only the “x” and “n” arguments. However, as you can see entering a third argument triggers our message. Furthermore, entering another function argument in place of an existing single argument also triggers our return value error message.

    How to solve this error

    Fixing the “unused argument error in r” message is quite simple, although there are several options you can use. In the first approach you can just make sure you get the correct argument names, this is the only solution for an existing r function but it can be used for a user-made one as well. Whether you are dealing with a vector, file, or some form of output command if you did not write the r function this is the only solution you have.

    # r unused argument error solution
    > expn = function(x,n)
    + {
    + xx = 1
    + for (i in 1:n) xx = xx*x
    + xx
    + }
    > expn(4, 5)
    [1] 1024

    While this example is user-defined it illustrates this approach quite well. In this case, we also exclude the labels making typing the wrong labels impossible.

    # unused argument error r solution
    > exps = function(x,n,s)
    + {
    + xx = 1
    + for (i in 1:n) xx = xx*x
    + xx+s
    + }
    > exps(x = 4,n =3,s = 5 )
    [1] 69

    The other option works only with a user-defined function, and that is to add additional unknown arguments to simply absorb the syntax mistake. This is a practical solution if you have repeated the same single argument mistake several times. By the way, you do not actually have to use it to fix the problem.

    This is a fairly simple problem to solve. If you wrote the base r function, then you have additional dataset options that you would not have if it were predefined. This problem may result from an easy to make mistake but it is easy to fix. It is part of the learning process of R programming.

    R Error Message: unused argument

    In R, if you try to call a function and pass arguments that are not defined, you will raise the error: unused arguments.

    The error message will indicate which argument is unnecessary, and you can remove it to solve the error.

    If you are using a built-in function, you can use the question mark ? before the function name to get the R documentation for the function. The documentation will give you the parameters for the function.

    The error can also occur if you have two libraries installed with the same function. To solve this error, you can use the package’s name (namespace) with the required function, for example, dplyr::select.

    This tutorial will go through the error in detail and how to solve it with code examples.


    Table of contents

    • Example: Unexpected Additional argument
      • Solution
    • Example: error in select unused arguments
      • Solution
    • Summary

    Example: Unexpected Additional argument

    Let’s look at a user-defined R function that takes two arguments.

    exponent <- function(x, n){ 
      result = x ** n
      return(result)
    }

    The function raises the first number x to the power of the second number n and returns the result. Next, we will try to call the function:

    exponent(x=2, n=3, s=10)

    Let’s run the code to see what happens:

    Error in exponent(x = 2, n = 3, s = 10) : unused argument (s = 10)

    We raise an error because the exponent function only expects two arguments, but we passed an additional third argument.

    Solution

    We can solve this error by removing the extra argument indicated by the error message. Let’s look at the revised code:

    exponent(x=2, n=3)

    Let’s run the code to see the result:

    [1] 8

    We successfully called the function and returned the result of 2 to the power of 3.

    Example: error in select unused arguments

    Let’s look at an example where we want to summarize a variable in the mtcars built-in dataset. First, let’s see the first six rows and column headers of the dataset:

    head(mtcars)
                       mpg cyl disp  hp drat    wt  qsec vs am gear carb
    Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
    Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
    Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
    Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
    Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
    Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

    Next, we will attempt to find the average horsepower (hp) grouped by cylinders (cyl):

    library(dplyr)
    library(MASS)
    
    > mtcars %>%
    + select(cyl, hp) %>%
    + group_by(cyl) %>%
    + summarize(avg_hp = mean(hp))

    Let’s run the code to see what happens:

    Error in select(., cyl, hp) : unused arguments (cyl, hp)

    The R interpreter raises the error because we have installed both the MASS and dplyr packages and the select() function from each package clashes.

    Solution

    We can solve this error by specifying the package’s name before calling the necessary function with two colons between the package name and the function. Let’s look at the revised code:

    library(dplyr)
    library(MASS)
    
    > mtcars %>%
    + dplyr::select(cyl, hp) %>%
    + group_by(cyl) %>%
    + summarize(avg_hp = mean(hp))

    Let’s run the code to see the result:

    # A tibble: 3 × 2
        cyl avg_hp
      <dbl>  <dbl>
    1     4   82.6
    2     6  122. 
    3     8  209. 

    We successfully calculated the average horsepower (hp) grouped by cylinders (cyl).

    Summary

    Congratulations on reading to the end of this tutorial! The R error: unused arguments can occur when you provide additional arguments to a function that R does not expect. The error message will indicate which argument is not required. The error can also occur if there are clashing functions from two or more imported libraries. You can specify the package name before calling the function to solve this error.

    For further reading on R related errors, go to the articles: 

    • How to Solve R Error: $ operator is invalid for atomic vectors
    • How to Solve R Error: Subscript out of bounds
    • How to Solve R Error in apply: dim(X) must have a positive length
    • How to Solve R Error: Cannot add ggproto plots together

    Go to the online courses page on R to learn more about coding in R for data science and machine learning.

    Have fun and happy researching!

    • Редакция Кодкампа

    17 авг. 2022 г.
    читать 1 мин


    Одна ошибка, с которой вы можете столкнуться в R:

    Error in select(., cyl, mpg) : unused arguments (cyl, mpg)
    

    Эта ошибка возникает, когда вы пытаетесь использовать функцию select() из пакета dplyr в R, но при этом загружен пакет MASS .

    Когда это происходит, R пытается вместо этого использовать функцию select() из пакета MASS и выдает ошибку.

    В этом руководстве рассказывается, как именно исправить эту ошибку.

    Как воспроизвести ошибку

    Предположим, мы пытаемся запустить следующий код, чтобы обобщить переменную в наборе данных mtcars в R:

    library(dplyr)
    library (MASS)
    
    #find average mpg grouped by 'cyl'
    mtcars %>%
     select(cyl, mpg) %>%
     group_by(cyl) %>%
     summarize(avg_mpg = mean(mpg))
    
    Error in select(., cyl, mpg) : unused arguments (cyl, mpg)
    

    Ошибка возникает из-за того, что функция select() из пакета MASS конфликтует с функцией select() из пакета dplyr.

    Как исправить ошибку

    Самый простой способ исправить эту ошибку — явно указать R использовать функцию select() из пакета dplyr, используя следующий код:

    library(dplyr)
    library (MASS)
    
    #find average mpg grouped by 'cyl'
    mtcars %>%
     dplyr::select(cyl, mpg) %>%
     group_by(cyl) %>%
     summarize(avg_mpg = mean(mpg))
    
    # A tibble: 3 x 2
     cyl avg_mpg
    1 4 26.7
    2 6 19.7
    3 8 15.1
    

    Код успешно выполняется, потому что dplyr::select явно указывает R использовать функцию select() из пакета dplyr вместо пакета MASS.

    Дополнительные ресурсы

    В следующих руководствах объясняется, как устранять другие распространенные ошибки в R:

    Как исправить в R: имена не совпадают с предыдущими именами
    Как исправить в R: более длинная длина объекта не кратна более короткой длине объекта
    Как исправить в R: контрасты могут применяться только к факторам с 2 или более уровнями

    Написано

    Редакция Кодкампа

    Замечательно! Вы успешно подписались.

    Добро пожаловать обратно! Вы успешно вошли

    Вы успешно подписались на кодкамп.

    Срок действия вашей ссылки истек.

    Ура! Проверьте свою электронную почту на наличие волшебной ссылки для входа.

    Успех! Ваша платежная информация обновлена.

    Ваша платежная информация не была обновлена.

    В этой статье мы рассмотрим подход к исправлению ошибки выбора неиспользуемых аргументов в языке программирования R.

    Ошибка при выборе неиспользуемых аргументов : компилятор R выдает эту ошибку, когда программист пытается использовать функцию select() пакета dplyr в R при условии, что загружен пакет MASS. R пытается вместо этого использовать функцию select() из пакета MASS, когда возникает такая ошибка. В этой статье основное внимание уделяется тому, как исправить эту ошибку.

    Error: Error in select(., cyl, mpg) : unused arguments (cyl, mpg) 

    Когда может возникнуть ошибка:

    Рассмотрим следующую программу R.

    Пример:

    library(dplyr)

    library(MASS)

    mtcars %>% select(cyl, mpg) %>% group_by(cyl) %>% summarize(avg_mpg = mean(mpg))

    Выход:

    Интерпретация: Компилятор выдает эту ошибку из-за конфликта между функцией select() из пакета MASS и функцией select() из пакета dplyr.

    Как исправить ошибку:

    Эту ошибку можно устранить, используя функцию select() непосредственно из пакета dplyr.

    Пример:

    R

    library(dplyr)

    library(MASS)

    mtcars %>%

      dplyr::select(cyl, mpg) %>%

      group_by(cyl) %>%

      summarize(avg_mpg = mean(mpg))

    Выход:

    Интерпретация: код успешно скомпилирован без каких-либо ошибок, поскольку dplyr явно использует функцию select() в пакете dplyr, а не в пакете MASS.

    Понравилась статья? Поделить с друзьями:
  • Error in samdump2
  • Error in rsync protocol data stream code 12 at io c 600
  • Error in resource files pubg что делать
  • Error in resource files pubg code 00000d06 0021
  • Error in resource files pubg code 00000d04 0021 ошибка