在R中实现就地修改算法 [英] Implementing in-place modification algorithms in R

查看:111
本文介绍了在R中实现就地修改算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚开始学习R时,我立即感到困惑:

Just starting to learn R and immediately I am confused:

鉴于这里的每个人(在SO上)如何一直说传值是主要使用R范式,是否有可能有效地实现暗示就地修改的算法(又名Quicksort等)?我的观察方式-如果我使用R执行此操作,则必须有效地返回中间结果,然后将其复制到另一种语言中,我将只修改由指针/引用传递的数组。我想念什么吗?

Given how everyone here (on SO) keeps saying that pass-by-value is one of the main R paradigms, is it possible to effectively implement algorithms that imply "modify in place" (aka quicksort and the likes)? The way I see it - if I do this using R I will have to return intermediate results effectively copying where in another language I will just modify an array passed by pointer/reference. Am I missing something?

我知道这可能是错误的语言,但确实如此吗?

I understand it may be the wrong language for that but is it really so?

推荐答案

有两种主要方法。如果可以控制调用约定,则可以将对象包装在环境中。

There are two main approaches. If you have control over the calling convention, you can wrap your objects in environments.

pointer <- new.env()
pointer$data <- iris
fn1 <- function(env) {
  numcols <- sapply(env$data, is.numeric)
  env$data[, numcols] <- env$data[, numcols] + 1
}
fn1(pointer) # pointer$data will now contain iris with all the numeric columns
             # incremented by 1. The full data set was never passed.

如果您没有控制权,可以尝试一些非标准评估的运动鞋,但要当心。

If you don't have control, you can try something sneakier with non-standard evaluation, but beware.

fn2 <- function(data) {
  numcols <- sapply(data, is.numeric)
  eval.parent(substitute(data[, numcols] <- data[, numcols] + 1))
}
fn2(iris)  # iris will now contain iris with all the numeric columns
           # incremented by 1. The full data set was also never passed.

在R版本3.1中,写入时复制将包括处理嵌套结构的功能,因此以上两项等同于

In version 3.1 of R, copy on write will include the ability to handle nested structures, so the above two would be equivalent to simply

fn3 <- function(data) {
  numcols <- sapply(data, is.numeric)
  data[, numcols] <- data[, numcols] + 1
  data
}
iris <- fn3(iris)

如果安装了R 3.1,则可以使用<$来验证性能要求c $ c> microbenchmark 这三个功能。

If you have R 3.1 installed, you can verify the performance claims yourself by using microbenchmark on these three functions.

这篇关于在R中实现就地修改算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆