Specifying column names in a data.frame changes spaces to “.”

后端 未结 4 1716
耶瑟儿~
耶瑟儿~ 2020-11-28 14:25

Let\'s say I have a data.frame, like so:

x <- c(1:10,1:10,1:10,1:10,1:10,1:10,1:10,1:10,1:10,1:10)
df <- data.frame(\"Label 1\"=x,\"Label 2\"=rnorm(10         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 14:45

    You can change an existing data frames names to contain spaces ie using your example

    x <- c(1:10,1:10,1:10,1:10,1:10,1:10,1:10,1:10,1:10,1:10)
    df <- data.frame("Label 1"=x,"Label 2"=rnorm(100))
    colnames(df) <- c("Label 1", "Label 2")
    head(df, 3)
    

    returns

      Label 1    Label 2
    1       1  0.2013347
    2       2  1.8823111
    3       3 -0.5233811
    

    and you can still access the columns using the $ operator, you just need to use double quotes eg

    df$"Label 2"[1:3]
    

    returns

    [1]  0.2013347  1.8823111 -0.5233811
    

    It seems rather inconsistent to me to auto-convert column names upon data.frame creation, but not to-do the same during column name alteration, but thats how R works at the moment.

提交回复
热议问题