简体   繁体   English

如何在r中转换函数的对象?

[英]How to transform the object of a function in r?

I want to create a function that transforms its object. 我想创建一个转换其对象的函数。

I have tried to transform the variable as you would normally, but within the function. 我试图像平常一样在函数内转换变量。

This works: 这有效:

vec <- c(1, 2, 3, 3)
vec <- (-1*vec)+1+max(vec, na.rm = T)
[1] 3 2 1 1

This doesn't work: 这不起作用:

vec <- c(1, 2, 3, 3)

func <- function(x){
  x <- (-1*x)+1+max(x, na.rm = T))
}

func(vec)
vec
[1] 1 2 3 3

R is functional so normally one returns the output. R是起作用的,因此通常返回一个输出。 If you want to change the value of the input variable to take on the output value then it is normally done by the caller , not within the function. 如果要更改输入变量的值以采用输出值,则通常由调用者完成,而不是在函数内完成。 Using func from the question it would normally be done like this: 使用问题中的func通常可以这样进行:

vec <- func(vec)

Furthermore, while you can overwrite variables it is, in general, not a good idea. 此外,虽然可以覆盖变量,但通常不是一个好主意。 It makes debugging difficult. 这使调试变得困难。 Is the current value of vec the input or output and if it is the output what is the value of the input? 是当前值vec的输入或输出,如果是输出什么是输入的值? We don't know since we have overwritten it. 我们不知道,因为我们已经覆盖了它。

func_ovewrite func_ovewrite

That said if you really want to do this despite the comments above then: 就是说,尽管您在上面的评论中仍然要这样做,那么:

# works but not recommended
func_overwrite <- function(x) eval.parent(substitute({
  x <- (-1*x)+1+max(x, na.rm = TRUE)
}))


# test
v <- c(1, 2, 3, 3)
func_overwrite(v)
v
## [1] 3 2 1 1

Replacement functions 更换功能

Despite R's functional nature it actually does provide one facility for overwriting although the function in the question is not really a good candidate for it so let us change the example to provide a function incr which increments the input variable by a given value. 尽管R具有功能性,但实际上它确实提供了一种覆盖功能,尽管问题中的功能并不是它的理想选择,因此让我们更改示例以提供一个函数incr ,该函数将输入变量增加给定值。 That is, it does this: 也就是说,它这样做:

x <- x + b

We can write this in R as: 我们可以在R中这样写:

`incr<-` <- function(x, value) x + value

 # test
 xx <- 3
 incr(xx) <- 10
 xx
 ## [1] 13

T vs. TRUE T与真

One other comment. 另一则评论。 Do not use T for true. 不要将T用作true。 Always write it out. 总是把它写出来。 TRUE is a reserved name in R but T is a valid variable name so it can lead to hard to find errors such as when someone uses T for temperature. TRUE是R中的保留名称,但T是有效的变量名称,因此它可能导致难以发现错误,例如有人将T用于温度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM