2013-08-28 81 views
1

我使用3个参数创建了用户定义的函数。当调用函数,如果我碰巧硬编码值,其中被注释掉一切正常,但如果我试图利用我收到以下错误参数行表示:将参数传递给用户定义的函数

Warning message: 
In `[<-.data.frame`(`*tmp*`, data$X == "Key1", , value = list(X = integer(0), : 
    provided 17 variables to replace 16 variables 

数据帧的数据包含16列!!!使用

代码:

Change <- function('Arc', Value, 'Key1'){ 

    data<-read.csv("matrix.csv") 

    #This statement works but the below does not ...... 
    #data[data$'X'=='C1',]$'OGB_OGB' <-(data[data$'X'=='C1',]$'OGB_OGB'/Value) 

    data[data$'X'=="Key1",]$"Arc" <-data[data$'X'=="Key1",]$"Arc"/Value  
    return(data) 
} 

tes<-Change("OGB_OGB",.3,"C1") 

我猜我的地方我搞乱了的弦parameters..please帮助

+1

我很su珍惜你的函数定义没有返回一个错误沿变化< - 函数中的意外字符串常量('Arc'' – mnel

回答

1

你不能定义一个函数

foo <- function('a') {'a'} 

这将返回错误

foo <- function('a'

所以你甚至没有创建一个函数。

创建时使用function一个功能,你必须通过它的命名参数的列表,

即。像foo <- function(a){}foo <- function(a = 1){}如果你想给它一个“默认”值。

在使用namessymbolscharacter strings

你也得到了一个很好的例子,财富(312)

library(fortunes) 
fortune(312) 

The problem here is that the $ notation is a magical shortcut and like any other magic if used incorrectly is likely to do the programmatic equivalent of turning yourself into a toad. -- Greg Snow (in response to a user that wanted to access a column whose name is stored in y via x$y rather than x[[y]]) R-help (February 2012)

因此你的功能可能是一些你指的是参数的函数像

Change <- function(Arc,Value, key = 'Key1') { 

data<-read.csv("matrix.csv") 
# calculate the logical vector only once 
# slightly more efficient 
index <- data[['X']]==key 
# you might consider index <- data[['X']] %in% key 
# if you wanted more than one value in `key` 
# replace as appropriate 
data[[Arc]][index] <- data[[Arc]][index]/Value 
# return the data 
return(data) 
} 


tes<-Change(Arc = "OGB_OGB",Value = .3,key = "C1") 
+1

你必须在快速拨号上有'财富(312)'。 – thelatemail

+0

@thelatemail - 我已经经常引用它... – mnel

+0

非常感谢你.....更改< - 函数('Arc',Value,'Key1')是一个错字..我打算把改变< - 功能(弧,值,键1) – user2723635

相关问题