Two seemingly equal ways of changing column names for R data.frame - only the other one works

后端 未结 2 1007
醉梦人生
醉梦人生 2021-01-26 04:25

I have a dataframe and I need to add suffix to some of the variable names. In my case that\'s all numerical variables after spreading a variable to wide format. Could someone ex

2条回答
  •  不知归路
    2021-01-26 04:50

    Your fist command contains syntax errors. We can fix it to:

    colnames(df[,2:ncol(df)]) <- paste0(names(df[,2:ncol(df)]), "_X")
    

    That doesn't return an error, but still doesn't work. You assign column names to a subset of a data.frame, but that subset is never stored and the command doesn't change the names of the full data.frame.

    You need to assign to a subset of the names:

    colnames(df)[2:ncol(df)] <- paste0(names(df)[2:ncol(df)], "_X")
    

提交回复
热议问题