Can't add constant to vector in R

后端 未结 1 891
轻奢々
轻奢々 2021-01-15 03:15

I don\'t know what is happening, but I can\'t seem to add a constant to a vector. For example, typing in the console c(1,2,3,4)+5 returns 15 instead of (6,7,8,9). What am I

相关标签:
1条回答
  • 2021-01-15 04:02

    Someone.... probably you ... has redefined the "+" function. It's easy to do:

    > `+` <- function(x,y) sum(x,y)
    > c(1,2,3,4)+5
    [1] 15
    

    It's easy to fix, Just use rm():

    > rm(`+`)
    > c(1,2,3,4)+5
    [1] 6 7 8 9
    

    EDIT: The comments (which raised the alternate possibility that c had instead been redefined as sum) are prompting me to add information about how to examine and recover from the alternative possibilities. You could use two methods to determine which of the two functions in the expression c(1,2,3,4) + 5 was the culprit. One could either type their names (with the backticks enclosing +), and note whether you got the proper definition:

    > `+`
    function (e1, e2)  .Primitive("+")
    > c
    function (..., recursive = FALSE)  .Primitive("c")
    

    Using rm on the culprit (the on that doesn't match above) remains the quickest solution. Using a global rm is an in-session brainwipe:

    rm(list=ls())  
    # all user defined objects, including user-defined functions will be removed
    

    The advice to quit and restart would not work in some situations. If you quit-with-save, the current function definitions would be preserved. If you had earlier quit-with-save from a session where the redefinition occurred, then not saving in this session would not have fixed the problem, either. The results of prior session are held in a file named ".Rdata and this file is invisible for both Mac and Windows users because the OS file viewer (Mac's Finder.app or MS's Windows Explorer) will not display file names that begin with a "dot". I suspect that Linux users get to see them by default since using ls in a Terminal session will show them. (It's easy to find ways to change that behavior in a Mac, and that is the way I run my device.) Deleting the .Rdata file is helpful in this instance, as well as in the situation where your R session crashes on startup.

    0 讨论(0)
提交回复
热议问题