将变量名称传递给r中的函数 [英] Pass variable name to a function in r

查看:118
本文介绍了将变量名称传递给r中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在函数调用中仅传递一个变量名称,并在函数内部使用它?



伪代码:

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


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

我想要做的是

  q(e)

并已返回

非e,e, e,非e,非e,e,e,非e,非e

// M




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

q(e)

Thx,
<您可以使用获取

$ $

解决方案

b
$ b

例如

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

编辑:正如艾丹Cully正确地说,那么你应该调用你的函数为 q(e)(即用字符串)


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") (i.e. with a string)

这篇关于将变量名称传递给r中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆