R更改包含加号或括号的列名

时间:2013-01-31 11:33:04

标签: r dataframe

我将data.frame的列名保存到R中的变量中。我的一些列名称包含加号+。将R保存到变量时,+会将.更改为+。我想保留for (u in 1:50) { k <- colnames[u] f <- append(f,k) } ## f is defined previously in my program ,这样我就可以在需要时自动选择这些列。

这是我用来将列名保存到变量中的命令:

file2 <- file1[,f]

这是我用来获取我需要的名字的命令:

column1+

示例: column1.在变量f中被命名为()

注意:括号/以及斜杠{{1}}

任何想法如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

这样问题仍然得到解答。将check.names选项设置为FALSE,同时使用data.frame阅读read.table

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

注意:正如@Roland在评论中所说,最好保持列名清洁而不是使用此参数。您还可能遇到某些功能自动将名称转换回来的情况。例如,

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

您必须知道具有check.names=FALSE的所有函数并记住正确使用它们。这至少是我能想到的一个问题。如果列没有冲突,那就更好了。

在列名中包含+等运算符也会干扰公式模型接口:

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

您需要使用lm(dat$b~dat[,'a+x'])