简体   繁体   中英

R changing column names containing plus or brackets

I am saving my column names of a data.frame into a variable in R . Some of my columns names contain a plus sign + . R changes the + into a . when saving it into a variable. I would like to retain the + so that i can pick these columns again automatically when I need them.

Here is the command I am using to save the column names into a variable:

for (u in 1:50) {
    k <- colnames[u]
    f <- append(f,k)
}
## f is defined previously in my program

Here is the command I am using to get the names I need again:

file2 <- file1[,f]

Example: column1+ is named column1. in the variable f

Note: This happened to the brackets () as well as slashes /

Any Ideas how I can get around this problem?

Just so the question remains answered. Set the option check.names to FALSE while reading the data.frame using read.table as:

read.table(file, check.names = FALSE)

Note: As @Roland says under the comments, it is better to keep the column names clean rather than using this parameter. You may also run into situations where certain functions automatically convert the names back. For example,

df <- data.frame('x+y' = 1:4, 'a+b' = 5:8, check.names = FALSE)
> df
#   x+y a+b
# 1   1   5
# 2   2   6
# 3   3   7
# 4   4   8

# Now adding a 3rd column, using `transform`
transform(df, c=9:12)
#   x.y a.b  c  # note that it reverts back
# 1   1   5  9
# 2   2   6 10
# 3   3   7 11
# 4   4   8 12

transform(df, c=9:12, check.names = FALSE)
#   x+y a+b
# 1   1   5
# 2   2   6
# 3   3   7
# 4   4   8

You'll have to know ALL functions that has check.names=FALSE and remember to use them correctly. This is at least one problem I could think of. Its rather better to have the columns without conflict.

Including operators such as + in column names can also interfer with the formula model interface:

dat <- data.frame('a+x'=c(1,2,3,4),b=c(2,4,6,8),check.names=FALSE)
lm(dat$b~dat$a+x)
Error in eval(expr, envir, enclos) : object 'x' not found

You would need to use lm(dat$b~dat[,'a+x']) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM