将Table,Column name作为Function Arguments传递时发出问题

时间:2016-05-31 09:54:21

标签: r function

CALL

dummy_func(bank,job) # never picks the column variable
                     # bank is the table where job is column name

功能

 dummy_func <- function(x, y) {


    for (level in unique(x$y)) {

       output<- bank[paste("dummy", level, sep = "_")] <- ifelse(x$y ==level, 1, 0)
    }

    return(output)


 }

1 个答案:

答案 0 :(得分:0)

如果您想传递数据帧&amp;列名作为函数的参数,然后用x [y]替换x $ y并将作业传递给dummy_func(bank,&#34; job&#34;)。

试试这段代码:

library(datasets)
data = iris
colnames(data)
y = "Species"

unique(data[y])

dummy_func <- function(x, y) {
  return(unique(x[y]))
}

dummy_func(data, y)
dummy_func(data, "Species")

如果你正在做x $ y,它会尝试寻找银行$ y而不是银行$ job。