r - How do I modify arguments inside a function? -


i have series of lines of code replace contents of existing column based on contents of column (i.e. creating categorical variable 'cut' function not applicable). new r , want write function perform task on data.frames without having insert , customize 50 lines of code each time.

x data frame, y categorical variable, , z other (string) variable. code works:

x$y <- "" x <- transform(x, y=ifelse(z=="alameda",20,"")) ... (many more lines) 

for example do:

d.f$loc <- "" d.f <- transform(d.f, loc=ifelse(county=="alameda",20,"")) # ... , on 

now want several dataframes , different columns instead of loc , county. however, neither of these functions produces desired results:

ab<-function(y,z,env=x) { env$y<-transform(env,y=ifelse(z=="alameda",20,"")) ... }  abc<-function(x,y,z) { x<-transform(x,y=ifelse(z=="alameda",20,"")) ... } 

both of these functions run without error not alter data frame x in way. doing wrong in calling environment or using function within function? seems simple question , not post if had not spent 5+ hours trying learn this. in advance!

r uses "call value" for objects. return value goes calling enviroment. parameter passing mechanism in r
can do 

ab <- function(x, y, z) {     x <- transform(x, y=ifelse(z=="alameda",20,""))     ...     return(x)  } 

if dataframes in list l you can do lapply(l, ab) or eventually lapply(l, ab, y=..., z=...) as result list of modified dataframes. btw: have at with() and within(), e.g. x$y <- with(x, ifelse(z=="alameda",20,""))

implicit returning value

there no need explicit call of return(...) - can implicit, i.e. using issue function returns value of last calculated expression:

ab <- function(x, y, z) {     x <- transform(x, y=ifelse(z=="alameda",20,""))     ...     x ### <<<<< last expression } 

here example how can situation:

ab <- function(x, y, z) {    x[, y] <- ifelse(x[,z]>12,20,99)    # ...    x ### <<<<< last expression } b <- bod # bod 1 of dataframes come r ab(b, "loc", "demand") 

Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -