[R] Updating DataFrame with Function
Ben Bolker
bolker at ufl.edu
Fri Jul 24 14:24:24 CEST 2009
BostonR wrote:
>
> This should be very simple but I am wrestling with updating a data frame
> from within a function. Here is a simple example:
> ### SET UP DATA FRAME
>> tFrame <- data.frame(T=c(1:5))
>>
>> tFrame
> T
> 1 1
> 2 2
> 3 3
> 4 4
> 5 5
>>
> ##### Simple function that updates with 1000
>> tUpdate<- function (x){
> + tFrame$T[x] <- 1000
> + }
>> tUpdate(5)
>> tFrame
> ############# Update within function fails
> T
> 1 1
> 2 2
> 3 3
> 4 4
> 5 5
>>
> ######## Update dataframe outside function with 100
>> tFrame[5,1] <- 100
>> tFrame
> T
> 1 1
> 2 2
> 3 3
> 4 4
> 5 100
>>
>
>
This is a fundamental issue with variable scope in functions.
When you modify a variable within a function it makes a local
copy. See section 10.5 of the introduction to R.
You either need to the function to return the changed value
tUpdate<- function (x){
tFrame$T[x] <- 1000
tFrame
}
tFrame <- tUpdate(5)
or use the <<- assignment operator.
--
View this message in context: http://www.nabble.com/Updating-DataFrame-with-Function-tp24641678p24643626.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list