无法在R中向向量添加常数 [英] Can't add constant to vector in R

查看:80
本文介绍了无法在R中向向量添加常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道发生了什么,但似乎无法向向量添加常量。例如,在控制台中键入c(1,2,3,4)+5返回15而不是(6,7,8,9)。我究竟做错了什么?
谢谢您的帮助。

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 doing wrong? Thank you for your help.

推荐答案

某人...。可能您...重新定义了 + 功能。这很容易做到:

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

易于修复,只需使用 rm()

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

编辑:评论(这引起了另一种可能性,即 c 而是被重新定义为 sum )提示我添加有关如何检查替代可能性并从中恢复的信息。您可以使用两种方法来确定 c(1,2,3,4)+ 5 表达式中的两个函数中的哪个是罪魁祸首。可以输入他们的名字(反引号内包含 + ),并记下您是否获得了正确的定义:

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")

在罪魁祸首上使用 rm (上面没有匹配的)仍然是最快的解决方案。使用全局rm是一次会期脑部擦拭:

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

退出和重启的建议在一些情况。如果退出保存,则将保留当前的函数定义。如果您早先在发生重定义的会话中退出了保存,那么不保存在该会话中也不会解决该问题。先前会话的结果保存在名为 .Rdata的文件中,并且Mac和Windows用户均看不到该文件,因为OS文件查看器(Mac的Finder.app或MS的Windows资源管理器)将不会显示以开头的文件名。我怀疑Linux用户默认会看到它们,因为在Terminal会话中使用 ls 会向他们显示。(很容易找到方法来更改Mac。这是我运行设备的方式。)在这种情况下,以及在启动时R会话崩溃的情况下,删除.Rdata文件很有用。

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.

这篇关于无法在R中向向量添加常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆