Search code examples
rfunctionvariablesget

How to use get()to call on a variable in a function in R?


I am trying to use get() in a function. Sometimes it works and sometimes it doesn't. The data is:

ID<-c("001","002","003","004","005","006","007","008","009","010","NA","012","013")
Name<-c("Damon Bell","Royce Sellers",NA,"Cali Wall","Alan Marshall","Amari Santos","Evelyn Frye","Kierra Osborne","Mohammed Jenkins","Kara Beltran","Davon Harmon","Kaitlin Hammond","Jovany Newman")
Sex<-c("Male","Male","Male",NA,"Male","Male",NA,"Female","Male","Female","Male","Female","Male")
Age<-c(33,27,29,26,27,35,29,32,NA,25,34,29,26)
data<-data.frame(ID,Name,Sex,Age)

It works in some codes like this:

FctPieChart <- function(data,Var){
  
  dVar <- data %>%
    filter(!is.na(get(Var))) %>%
    group_by(get(Var)) %>% #changes the name of the column to "`get(Var)`"
    summarise(Count = n()) %>%
    mutate(Total = sum(Count), Percentage = round((Count/Total),3))
}  
FctPieChart(data,"Sex")

And it doesn't work in some other codes like this:

FctPieChart <- function(data,var){
  x <- data %>% 
    select(get(var))
  x
  
}  
FctPieChart(data,"Sex")

It says:

<error/simpleError>
object 'Sex' not found

Does anyone know why?

Thank you very much in advance!

Best regards,

Stephanie


Solution

  • With dplyr::select() you don't need to use get(). Instead just useselect(var)

    > FctPieChart <- function(data,var){
       x <- data %>% 
         select(var)
       x
     }  
    > FctPieChart(data,"Sex")
          Sex
    1    Male
    2    Male
    3    Male
    4    <NA>
    5    Male
    6    Male
    7    <NA>
    8  Female
    9    Male
    10 Female
    11   Male
    12 Female
    13   Male