'names' attribute must be the same length as the vector

前端 未结 6 1905
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-15 19:00

Stuck on an error in R.

    Error in names(x) <- value : 
      \'names\' attribute must be the same length as the vector

What does thi

相关标签:
6条回答
  • 2020-12-15 19:41

    I have seen such error and i solved it. You may have missing values in your data set. Number of observations in every column must also be the same.

    0 讨论(0)
  • 2020-12-15 19:42

    The mistake I made that coerced this error was attempting to rename a column in a loop that I was no longer selecting in my SQL. This could also be caused by trying to do the same thing in a column that you were planning to select. Make sure the column that you are trying to change actually exists.

    0 讨论(0)
  • 2020-12-15 19:52

    For me, this error was because I had some of my data titles were two names, I merged them in one name and all went well.

    0 讨论(0)
  • 2020-12-15 19:57

    In the spirit of @Chris W, just try to replicate the exact error you are getting. An example would have helped but maybe you're doing:

      x <- c(1,2)
      y <- c("a","b","c")
      names(x) <- y
    
    Error in names(x) <- y : 
      'names' attribute [3] must be the same length as the vector [2]
    

    I suspect you're trying to give names to a vector (x) that is shorter than your vector of names (y).

    0 讨论(0)
  • 2020-12-15 20:02

    Depending on what you're doing in the loop, the fact that the %in% operator returns a vector might be an issue; consider a simple example:

    c1 <- c("one","two","three","more","more")
    c2 <- c("seven","five","three")
    
    if(c1%in%c2) {
        print("hello")
    }
    

    then the following warning is issued:

    Warning message:
    In if (c1 %in% c2) { :
      the condition has length > 1 and only the first element will be used
    

    if something in your if statement is dependent on a specific number of elements, and they don't match, then it is possible to obtain the error you see

    0 讨论(0)
  • 2020-12-15 20:03

    I want to explain the error with an example below:

    > names(lenses)
    [1] "X1..1..1..1..1..3"
    

    names(lenses)=c("ID","Age","Sight","Astigmatism","Tear","Class") Error in names(lenses) = c("ID", "Age", "Sight", "Astigmatism", "Tear", : 'names' attribute [6] must be the same length as the vector [1]

    The error happened because of mismatch in a number of attributes. I only have one but trying to add 6 names. In this case, the error happens. See below the correct one:::::>>>>

    > names(lenses)=c("ID")
    > names(lenses)
    

    [1] "ID"

    Now there was no error.

    I hope this will help!

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