Delete "X" in Header in R

Asked

Viewed 407 times

2

I am importing a csv file into the R and the name of each column is appearing the letter "X" before the original name. For example:
Field names in csv: 1.2_cidade; 2_UF.
Field names after import: X1.2_cidade; X2_UF.

How do I import without "X"?

  • Try names(dados) <- sub("^X", "", names(dados)). (dados is the name of the data frame.)

3 answers

4


Try to look at the argument check.names in ?read.csv.

read.csv("dados.csv", check.names = FALSE)

1

You may be putting too many arguments in the function read.csv, I had this problem sometimes, when I put the quote argument, and so on, now I usually just write the command like this and it usually works (my files. csv, are saved with decimal unit separated by comma), indicating that the separation of the columns is by ; and the decimal unit separates by ,.

read.csv("nome_do_arquivo.csv",sep=";",dec=",")

0

The problem is that R does not accept the variable name, function or column of data.frame starting with numeric, point or subtraction. That’s why it adds the X.

data <- data.frame('1.2_cidade' = c(1:2), '2_UF' = c(1:2))

data
   X_1.2_cidade X2_UF
1            1     1
2            2     2

The best solution is to rename the columns without the X, number, point or subtraction, because even forcing you may have, at some point, problems in the invocation.

colnames(data) <- sub("^[X0-9._]+", "", colnames(data))

data
  cidade UF
1      1  1
2      2  2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.