通过函数更新数据框不起作用 [英] Update data frame via function doesn't work

查看:21
本文介绍了通过函数更新数据框不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 R 时遇到了一个小问题……

I ran into a little problem using R…

在下面的数据框中

test <- data.frame(v1=c(rep(1,3),rep(2,3)),v2=0) 

我想在 v1 为 1 的行中更改 v2 的值.

I want to change values for v2 in the rows where v1 is 1.

test[test$v1==1,"v2"] <- 10

效果很好.

test
  v1 v2
1  1 10
2  1 10
3  1 10
4  2  0
5  2  0
6  2  0

但是,我需要在函数中做到这一点.

However, I need to do that in a function.

test <- data.frame(v1=c(rep(1,3),rep(2,3)),v2=0)

test.fun <- function (x) {
    test[test$v1==x,"v2"] <- 10
    print(test)
}

调用该函数似乎有效.

test.fun(1)
  v1 v2
1  1 10
2  1 10
3  1 10
4  2  0
5  2  0
6  2  0

但是,当我现在查看测试时:

However, when I now look at test:

test
  v1 v2
1  1  0
2  1  0
3  1  0
4  2  0
5  2  0
6  2  0

没用.是否有命令告诉 R 真正更新函数中的数据框?非常感谢您的帮助!

it didn’t work. Is there a command that tells R to really update the data frame in the function? Thanks a lot for any help!

推荐答案

test 在你的函数中是你全局环境中对象的copy(我假设这就是它被定义的地方).除非另有说明,否则赋值发生在当前环境中,因此函数内部发生的任何更改仅适用于函数内部的副本,而不适用于全局环境中的对象.

test in your function is a copy of the object from your global environment (I'm assuming that's where it is defined). Assignment happens in the current environment unless specified otherwise, so any changes that happen inside the function apply only to the copy inside the function, not the object in your global environment.

将所有必要的对象作为参数传递给函数是一种很好的形式.

And it's good form to pass all necessary objects as arguments to the function.

就我个人而言,我会在您的函数结束时return(test) 并在函数之外进行赋值,但我不确定您是否可以在实际情况下执行此操作.

Personally, I would return(test) at the end of your function and make the assignment outside of the function, but I'm not sure if you can do this in your actual situation.

test.fun <- function (x, test) {
    test[test$v1==x,"v2"] <- 10
    return(test)
}
test <- data.frame(v1=c(rep(1,3),rep(2,3)),v2=0)
(test <- test.fun(1, test))
#  v1 v2
#1  1 10
#2  1 10
#3  1 10
#4  2  0
#5  2  0
#6  2  0

如果绝对有必要直接在你的函数外修改一个对象,那么你需要告诉R你要将test的本地副本分配给test.GlobalEnv.

If it is absolutely necessary to modify an object outside your function directly, so you need to tell R that you want to assign the local copy of test to the test in the .GlobalEnv.

test.fun <- function (x, test) {
    test[test$v1==x,"v2"] <- 10
    assign('test',test,envir=.GlobalEnv)
    #test <<- test  # This also works, but the above is more explicit.
}
(test.fun(1, test))
#  v1 v2
#1  1 10
#2  1 10
#3  1 10
#4  2  0
#5  2  0
#6  2  0

以这种方式使用 assign<<- 是相当少见的,但许多有经验的 R 程序员会建议不要这样做.

Using assign or <<- in this fashion is fairly uncommon, though, and many experienced R programmers will recommend against it.

这篇关于通过函数更新数据框不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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