简体   繁体   中英

Pass variable name to a function in r

Is it possible to pass just a variable name in a function call and have it utilised as such within the function??

pseudocode:

q<-function(A){
    b<-(w%in%A.2|w%in%A.7)  
    factor(b,levels=c(F,T),labels=c("non-"A,A))}


w<-c(0:10)
e.2<-c(1,2)
e.7<-c(6,7)

what I´d like to do is

q(e)

and have returned

non-e,e,e,non-e,non-e,e,e,non-e,non-e

//M


q<-function(A) {
    a2<-get(paste(a,".2",sep=""))
    a7<-get(paste(a,".7",sep=""))
    b<-(w%in%a2|%in%a7) 
    factor(b,levels=c(F,T),labels=c(paste("non-",a,sep=""),a)) 
}

q("e")

Thx,

M

You can use get

For instance

var1 <- get(paste(e, ".2", sep=""))
var2 <- get(paste(e, ".7", sep=""))

EDIT: as Aidan Cully correctly says then you should call your function as q("e") (ie with a string)

您应该为“q”以外的函数选择不同的名称 - 否则您将永远无法完成;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM