我正在尝试从字符串列表中创建一个字符向量。我的最终目标是将其传递给make.names()
以创建数据框的列名。
temp<-data.frame(col1=c("use this row as name"),col2=c("use this row as name 2"))
make.names(temp[1,]) #fails
make.names(c("hi","xxx!@#$")) #works as expected
typeof(temp[1,])
typeof(c("hi","xxx!@#$"))
typeof(as.character(temp[1,]))
make.names(as.character(temp[1,]))
输出:
> temp<-data.frame(col1=c("use this row as name"),col2=c("use this row as name 2"))
> make.names(temp[1,])
[1] "X1" "X1"
> make.names(c("hi","xxx!@#$"))
[1] "hi" "xxx...."
> typeof(temp[1,])
[1] "list"
> typeof(c("hi","xxx!@#$"))
[1] "character"
> typeof(as.character(temp[1,]))
[1] "character"
> make.names(as.character(temp[1,]))
[1] "X1" "X1"
> temp[1,]
col1 col2
1 use this row as name use this row as name 2
目标:
>colnames(temp)
"use this row as name" "use this row as name 2"
以某种形式。只要列名称是半可理解的,间距和其他格式就不重要了。
答案 0 :(得分:3)
您可以unlist
数据框:
make.names(unlist(temp))
[1] "use.this.row.as.name" "use.this.row.as.name.2"
请注意,您的某些尝试失败了,因为temp
实际上是两列因素,当您在列表上调用as.character
时,会出现一些稍微不直观的行为。 (见?as.character
)。