Skip to content

Instantly share code, notes, and snippets.

@Kvit
Last active December 9, 2020 07:07
Show Gist options
  • Select an option

  • Save Kvit/cb70a02def6d19e01933202395b19350 to your computer and use it in GitHub Desktop.

Select an option

Save Kvit/cb70a02def6d19e01933202395b19350 to your computer and use it in GitHub Desktop.
R tricks and tips
# convert NA to Zero
log_pay_dt[,lapply(.SD,function(x){ifelse(is.na(x),0,x)}) ]
# convert NA to Zero for numberic cols only
cols = which( sapply(log_pay_dt, class) == "numeric" ) %>% names()
log_pay_dt[, (cols) := lapply( .SD, function(x){ifelse(is.na(x),0,x)} ), .SDcols = cols ]
# factor to character
col_class<-sapply(cpt_blend_summary, class)
cols=names(which(col_class=="factor"))
cpt_blend_summary[ , (cols) := lapply(.SD, as.character), .SDcols = cols]
# force numberic valuse
log_pay_dt[ , (pay_log_numeric_cols) := lapply(.SD, as.numeric), .SDcols = pay_log_numeric_cols]
#install R package for all users on digital ocean ubunty
# no library lock
sudo su - -c "R -e \"install.packages('dplyr', repos='http://cran.rstudio.com/', dependencies=TRUE, INSTALL_opts = c('--no-lock'))\""
# linux epoc time to posix
as.POSIXct(int_time, origin="1970-01-01")
# subset subcompenents of list
mylist <- list(1:5, 6:10, 11:15)
sapply(mylist, "[", c(2,3))
lst <- list('one','two','three')
a <- lst[1]
class(a)
## returns "list"
a <- lst[[1]]
class(a)
## returns "character"
https://www.r-bloggers.com/r-accessors-explained/
# extracting / mapping elements of the list
dt[,gearL1:=lapply(gearsL, function(x) x[2])]
dt[,gearS1:=sapply(gearsL, function(x) x[2])]
library (purrr)
# keep multiple names from array
l %>% keep(names(.) %in% c("a","b")) #keep mulitple names
map(got_chars, `[`, c("name", "culture", "gender", "born")) # map multiple names
res = modify(benefits, ~ list_modify(.x, acn=acn_in)) # modify each list element of an array
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment