Xinxin Yang's avatar
Xinxin Yang committed



#' Utility to copy data to clipboard for pasting to Excel
#'
#' @param d the data to copy
#' @param getRownames set to T to opy also row.names
#' @param ... any other parameter for passing to write.table
#' @return nothing
#' @export
#' @examples
#' write.excel(d);
write.excel=function(d,getRownames=F,...) {write.table(d,"clipboard-65000",sep="\t",row.names = getRownames,...)}





#' Updates selected elements of data stored in one DT with new one given in melted format
#'
#' The user provides the data.new: {id,variable,new value}. The function overwrites all existing id-column with the new values
#'
#' @param data.old The DT to update
#' @param data.new The data to insert. It must have three columns:  {id,variable,new value}. E.g. data.new=data.table("id"=c(810001100105),"variable"=c("AASBIO_CV"),value=c(999999))
#'
#'
#' @return a DT with the updated values
#' @export
#'
#' @examples
update_elements.DT = function(data.old,data.new) {

  id.var = names(data.new)[1]

  vars.to.replace = unique(data.new$variable)

  for(v in vars.to.replace) {

    setkeyv(data.old,id.var)

    data.col.new = merge(
      data.old[,mget(c(id.var,v))],
      data.new[variable==v,mget(c(id.var,"value"))],
      all.x=T
    )

    data.col.new[,value.merged:=ifelse(is.na(value),eval(parse(text = v)),value)]

    data.old[,(v):=data.col.new$value.merged]

  }


  return(data.old)


}