user1701545
user1701545

Reputation: 6190

Update a data.frame within an sapply function

Probably a simple question.

I'm running an sapply function in which I'd like to update a data.frame in addition to other operations the function does.

I thought this example code would work:

df <- NULL
res <- sapply(1:10, function(i){
  if(is.null(df)){
    df <- data.frame(itr=i,let = letters[i])
  } else{
    tmp.df <- data.frame(itr=i,let = letters[i])
    df <- rbind(df,tmp.df)
  }
  return(i)
})

In reality I return something more elaborate than just a index i. This is just a simplified example.

But df remains NULL after running the sapply.

How do I get df updated?

Upvotes: 0

Views: 548

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269471

The df defined in the function that is being assigned to is not the same df as the df defined outside the function. If you replace both occurrences of df <- with df <<- then it will work.

Although inefficient (because successively appending to an object in R is inefficient) you can successively append rows in a loop like this:

df <- NULL 
for(i in 1:10) df <- rbind(df, data.frame(itr = i, let = letters[i]))

Better would be to create a list of rows and then rbind them at once:

do.call("rbind", lapply(1:10, function(i) data.frame(itr = i, let = letters[i])))

Upvotes: 2

Related Questions