Update some columns of a R data frame

I wanted to code a R function that updates some columns in each row and not the entire row.

I declare a global variable to keep track of which row’s columns are being updated. I want to stop when the last row is reached.


youngdata <- function() {
    ydata <<- 1
}

This function creates a data frame which has 3 columns but valid data in only the first column. The 2nd and 3rd columns will be updated one row at a time.

youngdata <- function() {
  younggen <<- data.frame(lapply(as.Date('2014-08-06') + 0:0, seq, as.Date('2014/10/08'), '1 days'));
  younggen['eden'] <- 0
  younggen['survivor'] <- 0
  colnames(younggen) <- c("date","eden","survivor")
}

> younggen
date eden survivor
1 2014-08-06 0 0
2 2014-08-27 0 0
3 2014-09-17 0 0
4 2014-10-08 0 0


loadeddata <- function(df){
         if( ydata > nrow(df)){
             return
         }
         print("Loading new data")
         newdata <- data.frame(sample(1:40, 1, replace=F), sample(1:40, 1, replace=F),stringsAsFactors=FALSE)
         colnames(newdata) <- c("eden","survivor")    
         df[ydata,which(names(df) %in% names(newdata))]  <- newdata
 return(df)
 }

So every time the function loadeddata is called one row’s columns are updated and it stops when all the rows are finished. I increment ydata in another part of the code not shown here.

> younggen
date eden survivor
1 2014-08-06 2 16
2 2014-08-27 0 0
3 2014-09-17 0 0
4 2014-10-08 0 0

This code is used to test R-shiny’s ReactiveTimer that enables the code to dynamically update a graph with new data.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: