为什么使用 `<<-` 不受欢迎,我该如何避免它? [英] Why is using `<<-` frowned upon and how can I avoid it?

查看:42
本文介绍了为什么使用 `<<-` 不受欢迎,我该如何避免它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我关注了关于这里的讨论,我很好奇为什么使用<<- 在 R 中不受欢迎.它会导致什么样的混乱?

I followed the discussion over HERE and am curious why is using<<- frowned upon in R. What kind of confusion will it cause?

我还想了解一些有关如何避免 <<- 的提示.我经常使用以下内容.例如:

I also would like some tips on how I can avoid <<-. I use the following quite often. For example:

### Create dummy data frame of 10 x 10 integer matrix.
### Each cell contains a number that is between 1 to 6.
df <- do.call("rbind", lapply(1:10, function(i) sample(1:6, 10, replace = TRUE)))

我想要实现的是将每个数字向下移动 1,即所有 2 将变为 1,所有 3 将变为 2 等等.因此,所有 n 将变为 n-1.我通过以下方式实现了这一点:

What I want to achieve is to shift every number down by 1, i.e all the 2s will become 1s, all the 3s will be come 2 etc. Therefore, all n would be come n-1. I achieve this by the following:

df.rescaled <- df
sapply(2:6, function(i) df.rescaled[df.rescaled == i] <<- i-1))

在这种情况下,我怎样才能避免 <<-?理想情况下,我希望能够将 sapply 结果通过管道传输到另一个变量中:

In this instance, how can I avoid <<-? Ideally I would want to be able to pipe the sapply results into another variable along the lines of:

df.rescaled <- sapply(...)

推荐答案

第一点

<<-NOT 分配给全局变量的运算符.它尝试在最近的父环境中分配变量.所以,比如说,这会造成混乱:

<<- is NOT the operator to assign to global variable. It tries to assign the variable in the nearest parent environment. So, say, this will make confusion:

f <- function() {
    a <- 2
    g <- function() {
        a <<- 3
    }
}

那么,

> a <- 1
> f()
> a # the global `a` is not affected
[1] 1

第二点

您可以使用 Reduce 来做到这一点:

You can do that by using Reduce:

Reduce(function(a, b) {a[a==b] <- a[a==b]-1; a}, 2:6, df)

申请

apply(df, c(1, 2), function(i) if(i >= 2) {i-1} else {i})

但是

简单地说,这就足够了:

simply, this is sufficient:

ifelse(df >= 2, df-1, df)

这篇关于为什么使用 `&lt;&lt;-` 不受欢迎,我该如何避免它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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