[R] Function argument and scope

Bernardo Doré berdore at gmail.com
Sun Nov 13 23:09:03 CET 2016


Hello list,

my first post but I've been using this list as a help source for a while.
Couldn't live without it.

I am writing a function that takes a dataframe as an argument and in the
end I intend to assign the result of some computation back to the
dataframe. This is what I have so far:

myFunction <- function(x){
  y <- x[1,1]
  z <- strsplit(as.character(y), split = " ")
  if(length(z[[1]] > 1)){
    predictedWord <- z[[1]][length(z[[1]])]
    z <- z[[1]][-c(length(z[[1]]))]
    z <- paste(z, collapse = " ")
  }
  x[1,1] <- z
}

And lets say I create my dataframe like this:
test <- data.frame(var1=c("a","b","c"),var2=c("d","e","f"))

and then call
myFunction(test)

The problem is when I assign x[1,1] to y in the first operation inside the
function, x becomes a dataframe inside the function scope and loses the
reference to the dataframe "test" passed as argument. In the end when I
assign z to what should be row 1 and column 1 of the "test" dataframe, it
assigns to x inside the function scope and no modification is made on
"test".

I hope the problem statement is clear.

Thank you,

Bernardo Doré

	[[alternative HTML version deleted]]



More information about the R-help mailing list