R Error: names() applied to a non-vector

2020-06-30 06:12发布

问题:

I have a chunk of code which produces an error only the first time I run it. Strangely if I run it a second time I get no error (craziness definition?). Also the error does not show up always at the same position, I mean that if I add a few lines of comments the error message is printed after the comments and not after a specific instruction.

I cannot provide a reproducible example because I do not know where exactly the error comes from. The error is the following:

Error in names(frame)[names(frame) == "x"] <- name : 
  names() applied to a non-vector

I should specify that in my code I don't have -at least explicitly- a names() function.

回答1:

This is a tricky error. I was able to track down the reason and it seems to be that R has an object of the same name as the function cached. This is most likely if using an IDE such as RStudio a tab for View(df). Unless the tab is closed even running the function without code will give you this error. Likewise, if the tab is not closed not even removing all objects or doing a garbage collection will solve it. Once the tab is closed the error will be gone.



回答2:

I had the same error, and It was faulting on a particular function that I wrote. It was throwing the error whenever I loaded the function, even when the I commented out all the code in the function. I found that changing the variable name of my function stopped the error. My only guess is that there is some weird variable name conflict.



回答3:

I had the same error. The reason for it is something related to a file I saved long ago with the name "df", which is interfering with a current variable, also called df.

The solution however is straigthforward: Find the problematic line, by running the first line of the code, then clearing the global environment, and running it again. If no error occurs, add the next line, and so forth until the error occurs. Then, change the name of the variable in that line.



回答4:

Even I had the same error. The reason in my case was that there was another data frame with the same name as the function inside the function. I guess R throws this error when there is a type mismatch as well. In my case the name was first read as a function. When R came across the same name again, it would be looking for a function but instead found a data frame.

All I had to do was change the name of one of them and the error was gone.



回答5:

This error also appears in my code everytime when I tried to delete everything through remove(list = ls()). In my case the problem was, that I had an object named df (datatype = data.frame) and also had the View opened of a previous version of df. After closing the View the error disappeared.



回答6:

Just add

 as.vector(dataframe)

This works.