简体   繁体   English

在if语句中使用变量名的向量

[英]Using vector of variable names in an if statement

I'm fairly new to using R, but I've been encountering this issue a lot in what I'm trying to do. 我对使用R相当陌生,但是在尝试执行此操作时,我经常遇到此问题。 I'd like to apply a function to a specific column in a data.frame depending on the value passed to the containing function. 我想根据传递给包含函数的值将函数应用于data.frame中的特定列。 It would look something like this: 它看起来像这样:

myfunction <- function(var) {
        < do something to mydata$var >
}

Where var could be the name of any of the columns in mydata (a data.frame). 其中var可以是mydata (data.frame)中任何列的名称。

The issue is with the dataframe$var part of the code. 问题出在代码的dataframe$var部分。 I can't figure out how to dynamically call a variable name like that. 我不知道如何动态调用这样的变量名。 dataframe[,var] doesn't seem to work, nor does dataframe[,get(var)] or dataframe[,eval(var)] . dataframe[,var]似乎不起作用, dataframe[,get(var)]dataframe[,eval(var)]也不起作用。

I'd also like to use this same theory to loop through a vector of specific columns in mydata : 我也想使用相同的理论来遍历mydata中特定列的向量:

varlist <- c("var1","var2","var3")
for (var in varlist) {
    < do something to mydata$var >
}

But again, mydata$var is the problem. 但是同样, mydata$var是问题。

Any advice or help would be appreciated! 任何建议或帮助,将不胜感激!

Try this: 尝试这个:

test_frame = data.frame("a"=1:4,"b"=2:5,"c"=3:6)

varlist = c("a","c")

myfunction = function(var_name){
  return(mean(test_frame[,var_name]))
}

for (var in varlist){
  myfunction(var)
}

Or in a cleaner way... 或者以更清洁的方式...

sapply(varlist,myfunction)
  a   c 
2.5 4.5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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