Error in `[.data.frame`(ABCD, , -xyz) : object 'xyz' not found [duplicate]

StackOverflow https://stackoverflow.com/questions/21745021

  •  10-10-2022
  •  | 
  •  

Question

I'm trying to run a cor function to do PCA analysis. The dat frame I have clearly has the column name, I'm trying to ignore in the correlation. I'm getting an error message stating that object is not found.

Error in `[.data.frame`(ABCD, , -xyz) : object 'xyz' not found

In the above example 'xyz' is the column name. What should I be doing differently?

I'm trying to learn from the data set that is available in "HSAUR" package, called heptathlon.

> head(heptathlon)
                    hurdles highjump  shot run200m longjump javelin run800m score
Joyner-Kersee (USA)   12.69     1.86 15.80   22.56     7.27   45.66  128.51  7291

The column "score" is the eighth column and I get the error when I run:

> round(cor(heptathlon[,-score]), 2)
Error in `[.data.frame`(heptathlon, , -score) : object 'score' not found

If I substitute the column name with the column number, it seems to work. Clearly, I cannot use this approach for large data sets.

Était-ce utile?

La solution

You can't remove a column by name with a - sign, like you can with numerical indices.

But you can easily remove a column by name by using logical indexing. Here's an example, removing the column Sepal.Width from iris:

head(iris, 2)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa

i <- iris[,names(iris) != 'Sepal.Width']
head(i, 2)
  Sepal.Length Petal.Length Petal.Width Species
1          5.1          1.4         0.2  setosa
2          4.9          1.4         0.2  setosa

Note that - is not used, and the column name is quoted.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top