简体   繁体   中英

Why does arrow assignment in R not work in a transform function call?

I'm new to R and everything I have read has said it is generally preferred to the arrow assignment operator a <- 1 over the normal looking assignment operator a = 1 .

This was fine until I tried using the transform() function, where I noticed the assignment failed to actually occur.

So if I try the following the sum_x and mean_x are not added to the data frame. If I were instead to try updating an existing variable on the data frame it would not update.

my_data <- data.frame(x1 = c(2, 2, 6, 4), x2 = c(3,4,2,8))
transform(my_data, sum_x <- x1 + x2, mean_x <- (x1 + x2)/2)

However using the = assignment operator does work here.

my_data <- data.frame(x1 = c(2, 2, 6, 4), x2 = c(3,4,2,8))
transform(my_data, sum_x = x1 + x2, mean_x = (x1 + x2)/2)

I would like to understand why this is so I know when I should be using each method of assignment so as to not run into an unexpected pitfall.

You are told to prefer <- over = because there are some cases where the result might be ambiguous. This is, however, only for cases where you are assigning to a variable. In your example, you are not.

The equals = operator is used to assign values to function parameters.

The transform function is using the = syntax to allow you to modify the environment, but you are not directly assigning the results to those variables. transform is doing that for you and knows to do it because of the particular syntax you are using.

The trick is just to look at the help (?transform in this case) and follow it.

Adding an example to show why it matters:

mean(x = 1:5)

means find the mean of 1,2,3,4,5. It assigns 1:5 to the parameter x.

mean(a <- 1:5)

works, but doesn't do what you expected. There is no parameter a so it creates a variable a and assigns 1:5 to it. This is then positionally matched with x.

mean(a = 1:5)

doesn't work because there is no parameter called a in the mean function and the context makes R want to do parameter assignment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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