Home > Blockchain >  Assign values to slice of data.frame column returned from function in R
Assign values to slice of data.frame column returned from function in R

Time:04-01

I have a function that does some (complex) selecting of rows, and returns the corresponding values from one column. I then want to overwrite these values.

MWE

x = data.frame(a=c(1,2,3),b=c(4,5,6))
f = function(x,i){ return(x[x$a==i,'b']) }
f(x,2) <- 3

throws:

Error in f(x, 2) = 3 : could not find function "f<-"

Is there a way to assign these values from the function return?

No tidyverse please. Only base R.

CodePudding user response:

The function should be

f <- function(x, i, val) {
      if(missing(val)) {
       x<- x[x$a==i,]
     } else {
         x$b[x$a ==i] <- val
     }
    return(x)
}

Then, when we run the code

> f(x, 2, 3)
  a b
1 1 4
2 2 3
3 3 6

> f(x, 2) # missing the val
  a b
2 2 5

If we want to update the object, use <-

x <- f(x, 2, 3)

CodePudding user response:

An alternative would be to write your function in two ways: the original one, and a specific assignment function, so that the R parser will work on your original syntax:

f <- function(x, i) {
 return(x[x$a == i, 'b']) 
}

`f<-` <- function(x, i, value) {
  x[x$a == i, 'b'] <- value 
  return(x)
}

So now you can do:

f(x, 2)
#> [1] 5

f(x, 2) <- 3

x  
#>   a b
#> 1 1 4
#> 2 2 3
#> 3 3 6

f(x, 2)
#> [1] 3
  • Related