开发者

Relating to subset assignment, how can this syntax be useful? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

I have been reading the R Language Definition file. Recently I came across this syntax as a shortcut for subset assignment. For example

> x <- c(1:16)
> x[3:5] <- 13:15
> x
[1]  1  2 13 14 15  6  7  8  9 10 11 12 13 14 15 16

instead of

> x <- c(1:16)
&开发者_开发技巧gt; x[3:5] <- x[13:15]
> x

This can be made much more elaborate as in

> x[3:5] <- 13:15 + 15
> x
[1]  1  2 28 29 30  6  7  8  9 10 11 12 13 14 15 16
> x[3:5] <- 13:15*15:15
> x
[1]   1   2 195 210 225   6   7   8   9  10  11  12  13  14  15  16

To me this seems like a neat trick. On the other hand it seems like using it will inevitably lead to unreadable code.

Does anyone know of a good reason to use this kind of feature?


Subset assignment is invaluable when you only want to replace some of the elements of an object in R.

Consider this example when programming. We have an S3 generic and a method. We might like to print the call in the output

foo <- function(x, ...) {
    UseMethod("foo")
}

foo.default <- function(x, na.rm = TRUE) {
    obj <- list(fitted.values = mean(x, na.rm = na.rm),
                call = match.call())
    class(obj) <- "foo"
    obj
}

print.foo <- function(x, ...) {
    writeLines(strwrap("Call:"))
    print(x$call)
    cat("\n")
    print(fitted(x), ...)
}

Look what happens when we use this though:

R> set.seed(2)
R> foo(runif(10))
Call:
foo.default(x = runif(10))

[1] 0.5496559

It would be nicer if the call was just foo(x = runif(10)). We can rewrite our default method to resent the matched call using subset assignment:

foo.default <- function(x, na.rm = TRUE) {
    obj <- list(fitted.values = mean(x, na.rm = na.rm),
                call = match.call())
    obj$call[[1]] <- as.name("foo") ## here is the edit
    class(obj) <- "foo"
    obj
}

Which gives the much nicer:

R> set.seed(2)
R> foo(runif(10))
Call:
foo(x = runif(10))

[1] 0.5496559

The point is, that I don't need to know how to generate the appropriate matched call in it's entirety, I can just update one aspect of the call using subset assignment. This is a real boon when you just need to alter one or a few components of an object and not just a trick.


If you are objecting to overwriting the original object then try the following which returns a new object and leaves x unchanged:

xnew <- replace(x, 3:5, 13:15*15:15)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜