0

I am trying to find convert/cast a built in matrix state.x77 to a dataframe. But once casted using as.data.frame, the column "Life Exp" should be automatically casted to "Life.Exp"; however, when i used select() function to choose that column using Life.Exp or Life Exp, both do not exist. Am I casting it wrong?

library(dplyr)
library(tidyr)
state.x77 %>% as.data.frame %>% select(Frost,Life.Exp) %>% cor
Isabella
  • 27
  • 5

3 Answers3

1

Reinforcing the response of colleagues, as.data.frame converts the state.x77 matrix to data.frame, keeping the name of the original variables. The Life Exp variable contains space, interpreted by the R as a special character, so to select the Life Exp column in the data.frame, you must put (``). Therefore:

select (Frost, `Life Exp`)
Velton Sousa
  • 345
  • 1
  • 9
0

Try this:

library(dplyr)
library(tidyr)
state.x77 %>% as.data.frame() %>% select(Frost,`Life Exp`) %>% cor()

            Frost Life Exp
Frost    1.000000 0.262068
Life Exp 0.262068 1.000000
Duck
  • 39,058
  • 13
  • 42
  • 84
0

as.data.frame surprisingly does not change name of columns so the space in it remains, you can select the column with back quotes.

library(dplyr)
state.x77 %>% as.data.frame %>% select(Frost,`Life Exp`) %>% cor

However, if you use data.frame it adds the "." in between so now you can use

state.x77 %>% data.frame %>% select(Frost,Life.Exp) %>% cor
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213