GithubHelp home page GithubHelp logo

pryr's Introduction

pryr

Lifecycle: superseded R-CMD-check

pryr is superseded. Please use:

  • rlang for low-level R programming.
  • lobstr for object sizes & comparison.
  • sloop for OOP tools.

pryr's People

Contributors

hadley avatar jimhester avatar jranke avatar kevinushey avatar leeper avatar lionel- avatar richfitz avatar thomaskern avatar wrathematics avatar zero323 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pryr's Issues

Memory units in mem_used() after mathemematical operation

I want to convert units in mem_used() but I am confused by (1) how units are switched automatically and by (2) how units are changed but not the value. For example:

mem_used()
28.7 MB

# Operation 1 (I want to convert to GB)
mem_used()/1024
28.1 kB

# Operation 2 (I want to convert to kB)
mem_used()*1024
29.4 GB

But the operations above should have rather yielded for Operation # 1: '0.02803 GB' and for Operation # 2: '29388.8 kB'.

sessionInfo()
R version 3.2.1 (2015-06-18)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.9.5 (Mavericks)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] pryr_0.1.2

loaded via a namespace (and not attached):
[1] magrittr_1.5     tools_3.2.1      Rcpp_0.12.0      stringi_0.5-5    codetools_0.2-11 stringr_1.0.0   

Support for R6 classes in otype() and ftype()

Hi Hadley,

I am surprised that otype() and ftype() do not detect and report when the argument is an R6 object/method... yet. It would be great to have them support R6 in the future.

library(R6)
Person <- R6Class("Person",
  public = list(
    name = NULL,
    hair = NULL,
    initialize = function(name = NA, hair = NA) {
      self$name <- name
      self$hair <- hair
      self$greet()
    },
    set_hair = function(val) {
      self$hair <- val
    },
    greet = function() {
      cat(paste0("Hello, my name is ", self$name, ".\n"))
    }
  )
)
ann <- Person$new("Ann", "black")
otype(ann)

This example should return "R6", not "S3".

Cheers,
Florent

Compilation failure

Hello. I'm new to pryr, so just followed the instructions for installation from GitHub, but R just spits out the following:

> install_github("pryr")
Installing github repo pryr/master from hadley
Downloading pryr.zip from https://github.com/hadley/pryr/archive/master.zip
Installing package from C:\Users\me\AppData\Local\Temp\Rtmpkh0aRf/pryr.zip
Installing pryr
"C:/PROGRA~1/R/R-30~1.2/bin/x64/R" --vanilla CMD INSTALL  \
  "C:\Users\me\AppData\Local\Temp\Rtmpkh0aRf\devtools1f1c17d481c\pryr-master" --library="C:/Program  \
  Files/R/R-3.0.2/library" --install-tests 

* installing *source* package 'pryr' ...
** libs
ERROR: compilation failed for package 'pryr'
* removing 'C:/Program Files/R/R-3.0.2/library/pryr'
Error: Command failed (1)

pryr::object_size() may be skipping function environments or argument promises

I believe pryr::object_size() is not seeing some environments associated with function arguments (probably missing environments associated with promises). I have an example where the size reported by crude serialization is much larger than pryr::object_size().

The issue is related to the discussion from http://www.win-vector.com/blog/2015/04/how-and-why-to-return-functions-in-r/ and an example is below.

build1 <- function(z) {
  function() { print(z) }
}

build2 <- function(z) {
  force(z)
  function() { print(z) }
}

# try to print sizes of components
breakItDown = function(mod) {
  attr <- names(attributes(mode))
  if(is.function(mod)) {
     return(list(env=breakItDown(environment(mod)),
                 formals=breakItDown(formals(mod)),
                 body=breakItDown(body(mod)),
                 attr=attr))
  } 
  return(list(items=lapply(mod, FUN=function(x){length(serialize(x, NULL))}),
              attr=attr))
}


expmt <- function(touchEvertying=FALSE) {
  d <- data.frame(x=1:100000000)
  f1 <- build1(5)
  print(paste("pryr::object_size(f1)",pryr::object_size(f1)))
  print(paste('f1 serialize size',
           length(serialize(f1, NULL))))
  if(touchEvertying) {
    breakItDown(f1)
    print('zap f1')
  }
  print(paste("pryr::object_size(f1)",pryr::object_size(f1)))
  print(paste('f1 serialize size',
           length(serialize(f1, NULL))))
  f2 <- build2(5)
  print(paste("pryr::object_size(f2)",pryr::object_size(f2)))
  print(paste('f2 serialize size',
           length(serialize(f2, NULL))))
}

expmt(FALSE)
## [1] "pryr::object_size(f1) 33888"
## [1] "f1 serialize size 400029066"
## [1] "pryr::object_size(f1) 33888"
## [1] "f1 serialize size 400029070"
## [1] "pryr::object_size(f2) 33832"
## [1] "f2 serialize size 28388"

expmt(TRUE)
## [1] "pryr::object_size(f1) 33888"
## [1] "f1 serialize size 400029066"
## [1] "zap f1"
## [1] "pryr::object_size(f1) 33832"
## [1] "f1 serialize size 28388"
## [1] "pryr::object_size(f2) 33832"
## [1] "f2 serialize size 28388"

Various fun_* function issues

Might be worth noting that fun_args is exactly the same as the formalArgs function in the methods package.

If you want to keep it for consistency of naming, then fun_args and fun_calls should take the same input. (fun_args's input is x, whereas fun_calls takes obj.) I suggest f, to make it clear that the argument should be a function.

(I counted the number of functions with arguments named f, fn, fun, F, FN and FUN in packages on my machine. f was most common with 119 results, fun came second with 63.)

It's also worth having a fun_body function to look for functions that contain a string in their body.

#' @export
#' @rdname find_funs
fun_body <- function(f) deparse(body(f))

Usage examples:

fun_body(write.csv)
find_funs("package:utils", fun_body, fixed("write"))

Nonintuitive behaviours of %<c-%

The use of subsitute on the value argument in the %<c-% is (at least to me) unintuitive, since the function sometimes returns a vector, and sometimes returns a call.

(one %<c-% 1)
# [1] 1
class(one)
# [1] "numeric"

(two %<c-% (1 + 1))
# (1 + 1)
class(two)
# [1] "("
 is.call(two)
# [1] TRUE

I don't know whether this breaks anything, but consider removing the line

value <- substitute(value)

Secondly, R's precedence order gives unexpected results. This next assignment looks like it is correct:

three %<c-% 1 + 2
# [1] 3

but

three
# [1] 1

The assignment statement is equivalent to

(three %<c-% 1) + 2

not

three %<c-% (1 + 2)

There isn't anything obvious that you can do about this, but it's worth adding a note/example to the %<c-% help page to say that you must always wrap the RHS of the assignment in brackets or braces.

Export is_promise2

I found is_promise2 via this SO answer and it seems to be the only way to check that delayedAssign is working as expected outside of the GlobalEnv. Is there a reason it's not exported?

My use case:

e <- new.env(parent = emptyenv())
delayedAssign("var", 1:1e10, assign.env = e)

pryr::is_promise(e$var)
# Error: cannot convert to symbol (SYMSXP)

pryr:::is_promise2("var", e)
# [1] TRUE

Mapvalues

dtAnnonces$Parution <- mapvalues(x = dtAnnonces$Parution, from = c( "aujourd’hui ", " hier "), to = c("0","1"))

Maps correctly "hier" but not "aujourd'hui".

Error message is :
The following from values were not present in x: aujourd’hui

Functions for seeing the internal (hex, binary) representation of values

This would be handy for integers and doubles. E.g. something like

> binary(NaN)
[1] "01111111" "11111000" "00000000" "00000000" "00000000" "00000000" "00000000" "00000000"
> binary(0/0)
[1] "11111111" "11111000" "00000000" "00000000" "00000000" "00000000" "00000000" "00000000"

which shows that there are 'multiple' kinds of NaN (at least on 64bit architectures). Similar things with NA_real_ and NA_real_ + 1. A similar function hex for the hex representation. Or, perhaps a function like bytes(x, representation=c("binary", "hex")).

Do you think something like this this would fit in pryr? If so I can submit a pull request.

Update for R-devel

(from Kurt Hornik)

See http://cran.r-project.org/web/checks/check_results_pryr.html: this
currently fails for r-devel, because MM has replaced the tools internal
.make_S3_methods_stop_list by a non-internal nonS3methods.

Can you pls fix as necessary? (I guess test for nonS3methods in tools.)

(I hope this will actually be a moving target, and that we can
eventually get Luke to move to only using the S3 registry [and not the
package exports], and can finally get rid of this functions named like
S3 methods but not meant as S3 methods game.)

address() seems to give wrong answer when used inside a function on a function argument

I see a difference between the address reported by pryr::address and by .Internal(inspect()):

library(pryr)
#> Registered S3 method overwritten by 'pryr':
#>   method      from
#>   print.bytes Rcpp
set.seed(1)
x <- rnorm(10)
f <- function(data){
    force(data) # not needed; same issue without this line
    print(.Internal(inspect(data)))
    print(address(data))
    return(NULL)
}

myFun <- f(x)
#> @55cbd3bcbcd8 14 REALSXP g0c5 [NAM(7)] (len=10, tl=0) -0.626454,0.183643,-0.835629,1.59528,0.329508,...
#>  [1] -0.6264538  0.1836433 -0.8356286  1.5952808  0.3295078 -0.8204684
#>  [7]  0.4874291  0.7383247  0.5757814 -0.3053884
#> [1] "0x55cbd3046108"
address(x)
#> [1] "0x55cbd3bcbcd8"

Here's my setup, but note I see the same issue on R 3.5.0 on a Mac.

R version 3.6.1 (2019-07-05)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 18.04.2 LTS

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/openblas/libblas.so.3
LAPACK: /usr/lib/x86_64-linux-gnu/libopenblasp-r0.2.20.so

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] pryr_0.1.4           RhpcBLASctl_0.18-205 SCF_3.6.1           

loaded via a namespace (and not attached):
[1] compiler_3.6.1   magrittr_1.5     tools_3.6.1      Rcpp_1.0.2      
[5] stringi_1.4.3    codetools_0.2-15 stringr_1.4.0   

inspect() results in NAMED being incremented and a copy being made in [<-

z <- rnorm(10)
.Internal(inspect(z))
@29db210 14 REALSXP g0c5 [NAM(1)](len=10, tl=0) -1.05176,-0.477504,1.03435,1.18636,-0.633102,...

refs(z)
[1] 1
.Internal(inspect(z))
@29db210 14 REALSXP g0c5 [NAM(1)](len=10, tl=0) -1.05176,-0.477504,1.03435,1.18636,-0.633102,...
inspect(z)
<REALSXP 0x29db210>
.Internal(inspect(z))
@29db210 14 REALSXP g0c5 [NAM(2)](len=10, tl=0) -1.05176,-0.477504,1.03435,1.18636,-0.633102,...
refs(z)
[1] 2

z[5] <- 3
inspect(z)
<REALSXP 0x29dad78>
refs(z)
[1] 2
.Internal(inspect(z))
@29dad78 14 REALSXP g0c5 [NAM(2)](len=10, tl=0) -1.05176,-0.477504,1.03435,1.18636,3,...

inspect(): type: 17Error in inspect_(x, env) : Unimplemented type

Possibly related to #55. With:

> foo <- function(...) get("...", mode="...", envir=environment())
> x <- foo(a=1, b=2)
> str(x)
length 2, mode "...": 1 2
> str(x[1][[1]])
 promise to  NULL

you get:

> pryr::inspect(x)
type: 17Error in inspect_(x, env) : Unimplemented type
Enter a frame number, or 0 to exit   

1: pryr::inspect(x)
2: inspect_(x, env)
3: stop(list(message = "Unimplemented type", call = inspect_(x, env), cppstack
...
> pryr::inspect(x[1])
<VECSXP 0x5562f6e81d60>
  <PROMSXP 0x5562f6bae7f0>
  value: 
    [REALSXP 0x5562f6dd49a8]
  code: 
    <REALSXP 0x5562f6dd49a8>
  env: 
    NULL
> sessionInfo()
R version 3.6.1 Patched (2019-10-31 r77348)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 18.04.3 LTS

Matrix products: default
BLAS:   /home/hb/software/R-devel/R-3-6-branch/lib/R/lib/libRblas.so
LAPACK: /home/hb/software/R-devel/R-3-6-branch/lib/R/lib/libRlapack.so

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] compiler_3.6.1   pryr_0.1.4       magrittr_1.5     tools_3.6.1     
[5] Rcpp_1.0.2       stringi_1.4.3    codetools_0.2-16 stringr_1.4.0

address() changes the NAMED status

This illustrates the issue

> x = 1:5; .Internal(inspect(x)) 
@92fcbc8 13 INTSXP g0c3 [NAM(1)] (len=5, tl=0) 1,2,3,4,5
> address(x); .Internal(inspect(x))
[1] "0x92fcbc8"
@92fcbc8 13 INTSXP g0c3 [NAM(2)] (len=5, tl=0) 1,2,3,4,5

and a confusion caused by it, where x is replaced rather than updated

> x = 1:5; .Internal(inspect(x)); x[] = cumsum(x); .Internal(inspect(x))
@9684540 13 INTSXP g0c3 [NAM(1)] (len=5, tl=0) 1,2,3,4,5
@9684540 13 INTSXP g0c3 [NAM(1)] (len=5, tl=0) 1,3,6,10,15
> x = 1:5; address(x); x[] = cumsum(x); address(x)
[1] "0x9ebed00"
[1] "0x9ebec70"

RStudio crash when partial have args with names identical to that in the original f()

Hi, I'm a simple user of R, and not so experienced. After reading Advanced R programming I have started using partial() which I found very useful, however I found that when passing to partial() names identical to that in the original function RStudio crash.
I think to understand what happens, and obviously there is a simple solution (not using the same names!:)), however I will report here a reproducible example.

#Run on windows7 x64 , R 3.0.2

library(pryr)
x <- runif(1e4)
y <- runif(1e4)
test <- function(x, y) mean(x+y)
test <- partial(test, x=x)
test(y=y)

Thank you for your book, clearly let me progress with R.

clarification on srcref and function f

I was wondering if there is a simple explanation why functions created with function have a srcref attribute, whereas function created with f don't, but their bodies do. To add a touch of mystery, using f in a do.call inside another function makes even the body attributes go away. That means it's hard to use covr with pryr as the srcref attribute is used in that library. It'd be nice if function and f were absolutely interchangeable, in an ideal world. Thanks

library(pryr)
fplain = function(x) {x}
ff = f(x, {x})
f.do.call = function(...) do.call(f, c(dots(...), .env = parent.frame()))
fff = f.do.call(x, {x})
attributes(fplain)
# $srcref
# function(x) {x}
attributes(ff)
# NULL
attributes(fff)
# NULL
attributes(body(fplain))
# $srcref
# $srcref[[1]]
# {
# $srcref[[2]]
# x
# $srcfile
# $wholeSrcref
# fplain = function(x) {x}
attributes(body(ff))
# $srcref
# $srcref[[1]]
# {
# $srcref[[2]]
# x
# $srcfile
# $wholeSrcref
# ff = f(x, {x}
attributes(body(fff))
# NULL

Make promise explicit

By converting to S3 object with expression, environment and value parts. Provide function which returns a list for ...

Adding left-to-right composition

I've submitted a pull request #64 to add a chain function.

Sorry if I offend any functional programming purists. This is just compose in reverse order, so that functions are applied in the order they are put in, in contrast to the more mathematical interpretation of f %of% g I suppose this reads like f %then% g. It just feels more natural when one is accustomed to the piping framework.

The other thought was to call it rcompose for "reverse-compose", or I'm open to suggestions if it has a formal name in mathematics/FP.

EDIT: Realised this is probably more appropriate in purrr.

Installing gifthub

I am following the steps for installing certain packages within R Studios in order to download a github, here are the following commands that were given to me:
-install.packages("httr")
-install.packages("devtools")
-install.packages("NLP")
-install.packages("tm")
-install.packages("chron")
-library(httr)
-library(devtools)
Everything is going well until this points but when I reach the following command it tell me the following error:

install_github("aloth/sentiment/sentiment")
Downloading GitHub repo aloth/sentiment@master
from URL https://api.github.com/repos/aloth/sentiment/zipball/master
Installing sentiment
"C:/Program Files/R/R-33~1.1/bin/x64/R" --no-site-file --no-environ
--no-save --no-restore --quiet CMD INSTALL
"C:/Users/danie/AppData/Local/Temp/RtmpKahOPG/devtools9d03e8b2a91/aloth-sentiment-89ff33a/sentiment"
--library="C:/Users/danie/OneDrive/Documentos/R/win-library/3.3"
--install-tests

'C:\Program' is not recognized as an internal or external command,
operable program or batch file.
Error: Command failed (1)

unenclose has trouble with lists

When we create a list of closures, for example using
tag_fs <- setNames(lapply(void_tags, void_tag), void_tags))
where the tag function and the list tags can be found at http://adv-r.had.co.nz/dsl.html,
then unenclose(tag_fs$command) does not replace the variable tag by "command" but instead by the content of the entire list void_tags.

I am 90% sure this behavior is not intended and hence should be classified as an issue/bug, but I may be missing something.

object_size failing on environments when reloading a shiny generated ggplot with "load"

If I create a simple ggplot with shiny, save it (with save), and reload it (with load), then object_size exits with "Uimplemented type". It seems to be stumbling on the environments saved with the ggplot object because if I NULL them out it works fine. I created some code to recreate it with a simple plot.

library(ggplot2)
library(shiny)
library(pryr)

ui <- fluidPage(
    plotOutput("p")
) 

server <- function(input,output){
  output$p <- renderPlot({
    n <- 100
    df <- data.frame(x=rnorm(n),y=rnorm(n),frow=sample(1:3,n,T),fcol=sample(11:12,n,T))
    gs <- ggplot(df) + geom_point(aes(x,y)) + facet_grid(frow~fcol)
    print(object_size(gs)) # this works
    save(gs,file="gs.RData")
    gs
  })
} 
shinyApp(ui,server)

After your run this you can get the error on the console by entering:

>load("gs.RData")
>library(pryr)
>object_size(gs)
type: 17Error: Unimplemented type

If you NULL out the environments with:

>attr(gs$facet$cols,"env") <- NULL
>attr(gs$facet$rows,"env") <- NULL
>gs$plot_env <- NULL
>object_size(gs)
189 kB

Then object_size works fine again.

Note this is only with a plot generated and saved in Shiny. I stumbled across this while trying to optimize some big plots I am generating in Shiny, but this example was created to be small.

I thought about trying to fix it myself, but it is not clear to me how the environment could have been tagged wrong, I don't know the internals well enough.

I also couldn't get it to happen outside of shiny, maybe it has something to do with nested environments or something.

address() gives wrong address

cc @kevinushey. For example, I think these two addresses should be the same, but they're not:

> address(lm)
[1] "0x7fa60486b0e0"
> .Internal(inspect(lm))
@7fa603430a70 03 CLOSXP g1c0 [MARK,NAM(2)] 
[... other stuff trimmed ...]

But if you make a copy of lm, it seems to give the right address:

> lm2 <- lm
> address(lm2)
[1] "0x7fa603430a70"
> .Internal(inspect(lm2))
@7fa603430a70 03 CLOSXP g1c0 [MARK,NAM(2)] 
[... other stuff trimmed ...]

unenclose is not copying

Hey Hadley,

R is mapping memory different and is changing values after they have been evaluated. R 3.3.0 is changing variables after functions have been pryr::unenclose'd.

Any ideas on a fix?

This worked in R 3.2.latest (can't remember, but it was before I upgraded).

Small example:

# ans$A should return "A", all functions of ans currently return "C"

# plays bad memory tricks. 
run <- function() {
  myList <- list()

  for (item in c("A", "B", "C")) {
    my_fn <- function() { item }
    cat("my_fn: "); print(my_fn)
    cat("my_fn: "); print(pryr::unenclose(my_fn))
    myList[[item]] <- pryr::unenclose(my_fn)
    cat("myList:\n"); print(myList)
  }

  myList
}

ans <- run()
# my_fn: function() { item }
# <environment: 0x7fe7762670d8>
# my_fn: function () 
# {
#     "A"
# }
# myList:
# $A
# function () 
# {
#     "A"
# }
# 
# my_fn: function() { item }
# <environment: 0x7fe7762670d8>
# my_fn: function () 
# {
#     "B"
# }
# myList:
# $A
# function () 
# {
#     "B"
# }
# 
# $B
# function () 
# {
#     "B"
# }
# 
# my_fn: function() { item }
# <environment: 0x7fe7762670d8>
# my_fn: function () 
# {
#     "C"
# }
# myList:
# $A
# function () 
# {
#     "C"
# }
# 
# $B
# function () 
# {
#     "C"
# }
# 
# $C
# function () 
# {
#     "C"
# }

ans
# $A
# function () 
# {
#     "C"
# }
# 
# $B
# function () 
# {
#     "C"
# }
# 
# $C 
# function () 
# {
#     "C"
# }


# works as expected
run2 <- function() {
  myVec <- c("A", "B", "C")
  names(myVec) <- myVec
  myList <- lapply(myVec, function(item) {
    myItem <- force(item)
    my_fn <- function() { myItem }
    cat("my_fn: "); print(my_fn)
    my_fn <- pryr::unenclose(my_fn)
    environment(my_fn) <- globalenv()
    cat("my_fn: "); print(my_fn)
    my_fn
  })
  myList
}

ans2 <- run2()
# my_fn: function() { myItem }
# <environment: 0x7fe77624a150>
# my_fn: function () 
# {
#     "A"
# }
# my_fn: function() { myItem }
# <environment: 0x7fe77544ca00>
# my_fn: function () 
# {
#     "B"
# }
# my_fn: function() { myItem }
# <environment: 0x7fe7758e90e8>
# my_fn: function () 
# {
#     "C"
# }
ans2
# $A
# function () 
# {
#     "A"
# }
# 
# $B
# function () 
# {
#     "B"
# }
# 
# $C
# function () 
# {
#     "C"
# }

Release pryr 0.1.6

Prepare for release:

  • git pull
  • Check current CRAN check results
  • Polish NEWS
  • urlchecker::url_check()
  • devtools::check(remote = TRUE, manual = TRUE)
  • devtools::check_win_devel()
  • rhub::check_for_cran()
  • Update cran-comments.md
  • git push

Submit to CRAN:

  • usethis::use_version('patch')
  • devtools::submit_cran()
  • Approve email

Wait for CRAN...

  • Accepted πŸŽ‰
  • git push
  • usethis::use_github_release()
  • usethis::use_dev_version()
  • git push

test.bytes fails on PPC: endianness is ignored


R version 4.2.2 (2022-10-31) -- "Innocent and Trusting"
Copyright (C) 2022 The R Foundation for Statistical Computing
Platform: powerpc-apple-darwin10.8.0 (32-bit)

> library("testthat")
> library("pryr")
> 
> test_check("pryr")
[ FAIL 4 | WARN 0 | SKIP 0 | PASS 61 ]

══ Failed tests ════════════════════════════════════════════════════════════════
── Failure ('test-bytes.r:5'): bytes produces hex representations as expected ──
bytes(1L) not identical to c("00 00 00 01").
1/1 mismatches
x[1]: "01 00 00 00"
y[1]: "00 00 00 01"
── Failure ('test-bytes.r:10'): bytes produces hex representations as expected ──
bytes(1) not identical to "3F F0 00 00 00 00 00 00".
1/1 mismatches
x[1]: "00 00 00 00 00 00 F0 3F"
y[1]: "3F F0 00 00 00 00 00 00"
── Failure ('test-bytes.r:24'): bytes produces binary representations as expected ──
bits(1L) not identical to "00000000 00000000 00000000 00000001".
1/1 mismatches
x[1]: "00000001 00000000 00000000 00000000"
y[1]: "00000000 00000000 00000000 00000001"
── Failure ('test-bytes.r:29'): bytes produces binary representations as expected ──
bits(1) not identical to "00111111 11110000 00000000 00000000 00000000 00000000 00000000 00000000".
1/1 mismatches
x[1]: "00000000 00000000 00000000 00000000 00000000 00000000 11110000 00111111"
y[1]: "00111111 11110000 00000000 00000000 00000000 00000000 00000000 00000000"

[ FAIL 4 | WARN 0 | SKIP 0 | PASS 61 ]
Error: Test failures
Execution halted

names_c() fails due to http vs https

Ran show_c_source(.Internal(mean(x)) just now and it failed in names_c() at the line:

lines <- readLines("http://svn.r-project.org/R/trunk/src/main/names.c")

with an error (cannot open the connection). Change the URL to https seemed to fix it.

Forgot to add that I'm on OS X 10.10.3, R 3.3.0 and pryr 0.1.2.

False "copy" by track_copy(x) after 'x' is removed

The function returned by track_copy() falsely believe the object has been copied when it has actually been removed, e.g.

> library('pryr')
> x <- 1; x[1] <- 1
> tx <- track_copy(x)
> x[2] <- 2
> tx()
x copied
> x[1] <- 2
> tx()
> rm(x)
> tx()
x copied

This is because it only compares the "address" before and after, i.e.

> tx
function ()
{
    new <- address2(var, parent.frame())
    if (old == new)
        return(invisible(FALSE))
    if (!quiet)
        message(var, " copied")
    old <<- new
    invisible(TRUE)
}

Adding a

if (!exists(var, envir=parent.frame(), inherits=FALSE))
  return(invisible(FALSE))

at the top would fix this.

Better error message of `method_from_call()` on S3 methods

Hi,

method_from_call() works only on S4 methods and not on S3 methods.

Indeed, the doc says "find corresponding S4 method", but it never explicitly tells us it cannot find S3 methods.

If this is a technical limitation, I think it would be worth mentioning it in the doc, maybe in a @details section (and likewise if it is a WIP).

Moreover, it is not evident for a naive user (like me) whether a method is S3 or S4, and the error message is not very helpful:

pryr::method_from_call(mean(1:10))
#> Warning in formals(fun): argument is not a function
#> Error in getGeneric(f, !optional): no generic function found for 'mean'

Created on 2023-02-04 with reprex v2.0.2

Note that this reprex is oddly only really reproducible inside reprex(): in a fresh R session, a mean() call will work, but an anova() call will not.

Figure out why object_size() isn't right for S4

  A <- setClass("A", contains = "list", where = environment())
  expect_same(A)
  expect_same(new("A"))
  on.exit(removeClass("A", where = environment()))

  setClass("Foo", list(asdfasfasdadfsfdata = 'integer'))
  foo <- new("Foo", asdfasfasdadfsfdata = 1L)
  compare_size(foo)

[ftype] Question regarding the s3 method type

I have a question regarding the usage of pryr functions in own code.
Following is a function I've created:
f <- function(var) {pryr::ftype(var)}

Calling "ftype" directly for 't.data.frame' results in an expected output:

pryr::ftype(t.data.frame)
[1] "s3" "method"`

Calling the same 't.data.frame' from my function prints a wrong result:

f(t.data.frame)
[1] "function"

Is there some trick for "S3 method" recognition ?

seeking to use call_tree to get a list object

I am seeking to catch pryr::call_tree output, definitely, I failed.
Because I find the call_tree function use cat function to throw output.

I am trying to use pryr::call_tree to analysis the abstract grammar tree to leverage the power of %>% in dplyr to plot the function and data relationship, which is called DAG.

I found %>% have a great nature than other languages, when I am using Airflow, a Python workflow secheduler, the process of describing DAG is so tedious and I think it can be done in R in an elegant way.

In that, I am seeking a way to catch the abstract grammar tree in a list object or two data frame, which called as graph frame, to plot the workflow using ggplot2. And the key problem is how to get the list object...need your help.

>pryr::call_tree
function (x, width = getOption("width")) 
{
    if (is.expression(x) || is.list(x)) {
        trees <- vapply(x, tree, character(1), width = width)
        out <- str_c(trees, collapse = "\n\n")
    }
    else {
        out <- tree(x, width = width)
    }
    cat(out, "\n")
}
<environment: namespace:pryr>

what I am trying

> abc <- function(x) {
+   if (is.expression(x) || is.list(x)) {
+     trees <- vapply(x, tree, character(1), width = width)
+     out <- str_c(trees, collapse = "\n\n")
+   }
+   else {
+     out <- tree(x, width = width)
+   }
+   return(out)
+ }
> abc(123+2123)
Error in abc(123 + 2123) : could not find function "tree"

Trouble installing from source and from install_github

I had a compilation error message when installing from the copy of pryr-master that I downloaded from github today, so I took your advice and used install_github. Got the same error. I'm running R v3.1 64 bit on Windows. Any thoughts?

install_github("pryr")
Installing github repo pryr/master from hadley
Downloading master.zip from https://github.com/hadley/pryr/archive/master.zip
Installing package from C:\Users\jmiller\AppData\Local\Temp\2\RtmpKyjB1F/master.zip
Installing pryr
Installing dependencies for pryr:
testthat
trying URL 'http://cran.rstudio.com/bin/windows/contrib/3.1/testthat_0.8.1.zip'
Content type 'application/zip' length 222851 bytes (217 Kb)
opened URL
downloaded 217 Kb

package β€˜testthat’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
C:\Users\jmiller\AppData\Local\Temp\2\RtmpKyjB1F\downloaded_packages
"C:/PROGRA1/R/R-311.0/bin/x64/R" --vanilla CMD INSTALL
"C:\Users\jmiller\AppData\Local\Temp\2\RtmpKyjB1F\devtools40b0db33efc\pryr-master" --library="C:/Program
Files/R/R-3.1.0/library" --install-tests

  • installing source package 'pryr' ...
    ** libs

*** arch - i386
Warning: running command 'make -f "C:/PROGRA1/R/R-311.0/etc/i386/Makeconf" -f "C:/PROGRA1/R/R-311.0/share/make/winshlib.mk" SHLIB_LDFLAGS='$(SHLIB_CXXLDFLAGS)' SHLIB_LD='$(SHLIB_CXXLD)' SHLIB="pryr.dll" OBJECTS="RcppExports.o bytes.o inspect.o object_size.o promise.o slice.o typename.o"' had status 127
ERROR: compilation failed for package 'pryr'

  • removing 'C:/Program Files/R/R-3.1.0/library/pryr'
    Error: Command failed (1)

pryr Compliation Error 309 on Windows 7 x64 with x64 and x86 cygwin

I have several windows 7 machines that run RStudio. All of them have at least 64 bit Cygwin installed and some also have 32 bit installed. Here is uname -a on Cygwin 64-bit:

CYGWIN_NT-6.1 5X9TXV1 1.7.29(0.272/5/3) 2014-04-07 13:46 x86_64 Cygwin

They all have the most recent version of RTools, here is find_rtools(debug=TRUE):
Scanning path...
ls : c:\Rtools\bin\ls.exe
gcc: c:\Rtools\GCC-46~1.3\bin\gcc.exe
VERSION.txt
Rtools version 3.1.0.1942
Version: 3.1
[1] TRUE

I've tried this on 3 machines so far and it's failed on all three. Here is what I get:

install_github("hadley/pryr")
Installing github repo pryr/master from hadley
Downloading master.zip from https://github.com/hadley/pryr/archive/master.zip
Installing package from C:\Users\cbortz\AppData\Local\Temp\RtmpMfa9AM/master.zip
Installing pryr
"C:/PROGRA1/R/R-311.0/bin/x64/R" --vanilla CMD INSTALL
"C:\Users\cbortz\AppData\Local\Temp\RtmpMfa9AM\devtools754481c1ba3\pryr-master"
--library="C:/Users/cbortz/Documents/R/win-library/3.1"
--install-tests

  • installing source package 'pryr' ...
    ** libs

*** arch - i386
Warning: running command 'make -f "C:/PROGRA1/R/R-311.0/etc/i386/Makeconf" -f "C:/PROGRA1/R/R-311.0/share/make/winshlib.mk" SHLIB_LDFLAGS='$(SHLIB_CXXLDFLAGS)' SHLIB_LD='$(SHLIB_CXXLD)' SHLIB="pryr.dll" OBJECTS="RcppExports.o bytes.o inspect.o object_size.o promise.o slice.o typename.o"' had status 309
ERROR: compilation failed for package 'pryr'

  • removing 'C:/Users/cbortz/Documents/R/win-library/3.1/pryr'
    Error: Command failed (1)

Finally, here is what a system call to g++ produces:

system('g++ -v')
Using built-in specs.
COLLECT_GCC=c:\Rtools\GCC-46~1.3\bin\G__1.EXE
COLLECT_LTO_WRAPPER=c:/rtools/gcc-46
1.3/bin/../libexec/gcc/i686-w64-mingw32/4.6.3/lto-wrapper.exe
Target: i686-w64-mingw32
Configured with: /data/gannet/ripley/Sources/mingw-test3/src/gcc/configure --host=i686-w64-mingw32 --build=x86_64-linux-gnu --target=i686-w64-mingw32 --with-sysroot=/data/gannet/ripley/Sources/mingw-test3/mingw32mingw32/mingw32 --prefix=/data/gannet/ripley/Sources/mingw-test3/mingw32mingw32/mingw32 --with-gmp=/data/gannet/ripley/Sources/mingw-test3/mingw32mingw32/prereq_install --with-mpfr=/data/gannet/ripley/Sources/mingw-test3/mingw32mingw32/prereq_install --with-mpc=/data/gannet/ripley/Sources/mingw-test3/mingw32mingw32/prereq_install --disable-shared --enable-static --enable-targets=all --enable-languages=c,c++,fortran --enable-libgomp --enable-sjlj-exceptions --enable-fully-dynamic-string --disable-nls --disable-werror --enable-checking=release --disable-win32-registry --disable-rpath --disable-werror CFLAGS='-O2 -mtune=core2 -fomit-frame-pointer' LDFLAGS=
Thread model: win32
gcc version 4.6.3 20111208 (prerelease) (GCC)

Thoughts?

f(identity) thinks identity is a variable

Believe it or not, I have a use case with argumentless functions that return a function, such as

function()
  identity

Unfortunately

> f(identity)
function (identity) 
identity

ftype does not work on S4 group generics?

> Arith
groupGenericFunction for "Arith" defined from package "base"
  belonging to group(s): Ops 

function (e1, e2) 
standardGeneric("Arith")
<bytecode: 0x0000000011d89498>
<environment: 0x0000000007abc788>
Methods may be defined for arguments: e1, e2
Use  showMethods("Arith")  for currently available ones.
> isGeneric('Arith')
[1] TRUE
> ftype(Arith)
[1] "function"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.