[英]How to use get()to call on a variable in a function in R?
I am trying to use get() in a function.我正在尝试在 function 中使用 get()。 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斯蒂芬妮
With dplyr::select()
you don't need to use get()
.使用dplyr::select()
您不需要使用get()
。 Instead just use select(var)
相反,只需使用select(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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.