sendHelpPlease
sendHelpPlease

Reputation: 45

Why are these functions different?

I am not sure why I get different results from these functions.

change_it1 <- function(x) {
  x[x == 5] <- -10
}
change_it2 <- function(x) {
  x[x == 5] <- -10
  x
}
x <- 1:5
x <- change_it1(x)
x
x <- 1:5
x <- change_it2(x)
x

Why do both functions not change x in the same way as?

x[x==5] <- -10

Upvotes: 0

Views: 40

Answers (1)

MrFlick
MrFlick

Reputation: 206546

The assignment operator <- is really a function that has the side effect of changing a variables value. But as a function, it also invisibly returns the value that was used on the right hand side for assignment. We can force the invisible value to be seen with a print(). For example

x <- 1:2
print(names(x) <- c("a","b"))
# [1] "a" "b"

or again with subsetting

print(x[1] <- 10)
# [1] 10
print(x[2] <- 20)
# [1] 20
x
#  a  b 
# 10 20 

See in each case the assignment returned the right-hand-side value and not the updated value of x. Functions will return whatever value was returned by the last expression. In the first case, you are returning the value returned by the assignment (which is just the value -10) and in the second case you are explicitly returning the updated x value.

The functions both change x in the same way (at least in the scope of the function), but you are just not returning the updated x value in both cases.

Upvotes: 3

Related Questions