[R] Function argument and scope

Bernardo Doré berdore at gmail.com
Mon Nov 14 11:46:04 CET 2016

Thank you all for replying so quickly.

You are right, I ran into that. You can see as.character() being called to
remedy the situation you described. I dropped the factors from the data
frame in a line outside the function. Creating the dataframe with
stringsAsFactors = F is the easiest way to go. Tks.

@Thomas, @Jeremiah
R really creates a copy and forgets the reference. That was clearly visible
in the debugger. In an earlier version of this I was returning a list of
the compute values. I will go back to that.

Tks a lot for helping me with this.

Bernardo Doré

> On Sun, Nov 13, 2016 at 2:09 PM, Bernardo Doré <berdore at gmail.com> wrote:
>> 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]]
>> ______________________________________________
>> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posti
>> ng-guide.html
>> and provide commented, minimal, self-contained, reproducible code.

	[[alternative HTML version deleted]]

More information about the R-help mailing list