Sulfat
Sulfat

Reputation: 3

Changing dataframe values with a function

My problem is that i want to use a function to change a random value to NA in a global data frame.

df is a dataframe with 230 rows and 2 columns.

abstract code:

emptychange<- function(x){
  placenumber <- round(runif(1,min= min(1),max=max(nrow(x))))
  x[placenumber,2] <<- NA
}

emptychange(df)

The Error is:"Error in x[placenumber, 2] <<- NA : object 'x' not found".

I think the mistake is, that r searches for the global variable 'x' and doesn't use the function x-value (in this case df). How can I fix this? Thanks!

Upvotes: 0

Views: 191

Answers (2)

IRTFM
IRTFM

Reputation: 263331

f you want this to be done at the console, you can just use sample-ing from the row count inside the [<- function:

> df1 <-data.frame(x = 1, y = 1:10)
> df1[sample(nrow(df1), 1) , 2] <- NA
> df1
   x  y
1  1  1
2  1  2
3  1  3
4  1  4
5  1  5
6  1 NA
7  1  7
8  1  8
9  1  9
10 1 10

If you want to destructively change the dataframe argument given to a function you should instead assign the value which is returned back to the original name:

>  randNA.secCol <- function(df) {df[sample(nrow(df), 1) , 2] <- NA; df}
> df1 <-data.frame(x = 1, y = 1:10)
> df1 <- randNA.secCol(df1)

Best practice in R is avoidance of the use of the <<- function.

Upvotes: 1

Pierre Lapointe
Pierre Lapointe

Reputation: 16277

This works. The problem was this: <<- NA Double arrows are used when you want to assign a value to an object outside the function. In you case, your x is inside the function.

df1 <-data.frame(x = 1, y = 1:10)

emptychange<- function(x){
  placenumber <- round(runif(1,min= min(1),max=max(nrow(x))))
  x[placenumber,2] <- NA
  return(x)
}

emptychange(df1)

Upvotes: 1

Related Questions