Is there a way in R to have a variable evaluated as a column name when creating a data frame (or in similar situations like using cbind)?
在R中是否有一种方法在创建数据帧时将变量作为列名进行计算(或者在类似的情况下,如使用cbind)?
For example
例如
a <- "mycol";
d <- data.frame(a=1:10)
this creates a data frame with one column named a
rather than mycol
.
这将创建一个数据框架,其中一个列名为a而不是mycol。
This is less important than the case that would help me remove quite a few lines from my code:
这比帮助我从代码中删除几行代码的情况要重要得多:
a <- "mycol";
d <- cbind(some.dataframe, a=some.sequence)
My current code has the tortured:
我现在的代码有折磨:
names(d)[dim(d)[2]] <- a;
which is aesthetically barftastic.
这是审美barftastic。
3 个解决方案
#1
11
> d <- setNames( data.frame(a=1:10), a)
> d
mycol
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
#2
8
Is structure(data.frame(1:10),names="mycol")
aesthetically pleasing to you? :-)
结构(data.frame(1:10),names="mycol")对你来说是否美观?:-)
#3
2
just use colnames after creation. eg
创建后只需使用colname。如
a <- "mycolA"
b<- "mycolB"
d <- data.frame(a=1:10, b=rnorm(1:10))
colnames(d)<-c(a,b)
d
mycolA mycolB
1 -1.5873866
2 -0.4195322
3 -0.9511075
4 0.2259858
5 -0.6619433
6 3.4669774
7 0.4087541
8 -0.3891437
9 -1.6163175
10 0.7642909
#1
11
> d <- setNames( data.frame(a=1:10), a)
> d
mycol
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
#2
8
Is structure(data.frame(1:10),names="mycol")
aesthetically pleasing to you? :-)
结构(data.frame(1:10),names="mycol")对你来说是否美观?:-)
#3
2
just use colnames after creation. eg
创建后只需使用colname。如
a <- "mycolA"
b<- "mycolB"
d <- data.frame(a=1:10, b=rnorm(1:10))
colnames(d)<-c(a,b)
d
mycolA mycolB
1 -1.5873866
2 -0.4195322
3 -0.9511075
4 0.2259858
5 -0.6619433
6 3.4669774
7 0.4087541
8 -0.3891437
9 -1.6163175
10 0.7642909