Why am I getting X. in my column names when reading a data frame?

后端 未结 5 676
迷失自我
迷失自我 2020-11-28 06:03

I asked a question about this a few months back, and I thought the answer had solved my problem, but I ran into the problem again and the solution didn\'t work for me.

5条回答
  •  感动是毒
    2020-11-28 06:30

    When the column names don´t have correct form, R put an "X" at the start of the column name during the import. For example it is usually happening when your column names starts with number or some spacial character. The check.names = FALSE cause it will not happen - there will be no "X". However some functions may not work if the column names starts with numbers or other special character. Example is rbind.fill function.

    So after the application of that function (with "corrected colnames") I use this simple thing to get rid of the "X".

    destroyX = function(es) {
      f = es
      for (col in c(1:ncol(f))){ #for each column in dataframe
        if (startsWith(colnames(f)[col], "X") == TRUE)  { #if starts with 'X' ..
          colnames(f)[col] <- substr(colnames(f)[col], 2, 100) #get rid of it
        }
      }
      assign(deparse(substitute(es)), f, inherits = TRUE) #assign corrected data to original name
    }
    

提交回复
热议问题