gsubfn 0.70

13 views
Skip to first unread message

Gabor Grothendieck

unread,
Mar 30, 2018, 11:09:26 AM3/30/18
to sqldf
gsubfn version 0.7 was released to CRAN earlier this month and should now be on all mirrors.

It's main purpose is to pass R CMD check on R devel but it does include the new function, transform2.  Also gsubfn 0.6-7 which had not been released to CRAN and was only available on github had added list on the left hand side of an assignment to provide multiple assignment from functions and this is now available through this release as well.

Transforming columns in data frames

transform2 is like transform but whereas transform uses the first argument as the source of free variables on the right hand sides of arguments, transform2 first looks in the other arguments and only after that in the first argument.  It automatically determines dependencies so that the second and subsequent arguments can be in any order.  For example,

  transform2(BOD, y = x+1, x = Time + 1)
  ##  Time demand y x
  ## 1    1    8.3 3 2
  ## 2    2   10.3 4 3
  ## etc.

transform2 differs from transform and dplyr::mutate because in transform the right hand sides are looked up in the first argument only and in mutate it proceeds from left to right whereas in transform2 it figures out the dependencies.  In the above example, x was defined after y yet it still works. The above example would give an error in both transform and mutate.

To write the above example using transform one would need to write this double transform where y is specified twice or a rearrangement of column order afterwards.

  transform(transform(BOD, y = NA, x = Time + 1), y = x + 1)

mutate (in dplyr) could do it with one mutate but would still require specifying y twice or else rearranging the columns afterwards.

  library(dplyr)
  mutate(BOD, y = NA, x = Time + 1, y = x + 1)

transform may be more suitable in some situations (e.g. if you want to swap columns) and transform2 in others (new columns depend on other new columns).

Multiple assignment

This is supported by writing list[...] on the left hand side of an assignment.  Square brackets, not round brackets, are used.  It is easiest to understand by example.  These and other examples are in the help file: help("list", "gsubfn")

  # swap a and b without explicitly creating a temporary 
  a <- 1; b <- 2 list[a,b] <- list(b,a) 

  # get eigenvectors and eigenvalues.  
  # New variables e_val and e_vec are created to hold these.
  list[e_val, e_vec] <- eigen(cbind(1,1:3,3:1)) 

  # get first two components of linear model ignoring rest
  list[Coef, Resid] <- lm(rnorm(10) ~ seq(10)) 

Reply all
Reply to author
Forward
0 new messages