I created a user defined function with 3 parameters. While calling the function if I happen to hardcode the value as indicated in the line which is commented everything works well but if I try to make use of parameters I am getting the following error:
Warning message:
In `[<-.data.frame`(`*tmp*`, data$X == "Key1", , value = list(X = integer(0), :
provided 17 variables to replace 16 variables
The data frame data contains 16 columns !!!
code used :
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")
I am guessing somewhere i am messing up the strings parameters..please help
You can't define a function
foo <- function('a') {'a'}
This will return the error
foo <- function('a'
So you aren't even creating a function.
When creating a function using function
, you must pass it an list of named arguments,
ie. something like foo <- function(a){}
or foo <- function(a = 1){}
if you want to give it a "default" value.
Within the function you refer to the arguments using names
( symbols
not character strings
)
You have also got a great example fortune(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)
Therefore your function could be something like
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")
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.