Assigning colnames() to specific column of a data frame

前端 未结 3 465
梦谈多话
梦谈多话 2021-01-14 11:22

I have a question about the colnames function in the base package

Let\'s say you have a data.frame, as follows:

df <- data.frame(var         


        
3条回答
  •  青春惊慌失措
    2021-01-14 11:39

    The reason your version does not do what you expect is that df[1] creates a temporary data frame in memory, the colnames function then changes the name of the 1 column in this temporary data frame (not your original data frame), but then nothing else is done with the temporary df so it is silently discarded. Your original data frame was never touched, so the next time you do colnames(df[1]) a new temporary df is created copying from your unmodified original and the colname is returned.

    Changing the order of calling colnames and subsetting does what you want as the other answers show.

提交回复
热议问题