Let's say I have the following data-frame:
a<-data.frame(A=3,B=9,C=10,D=6)
b<-data.frame(A="i3",B="i9",C="i10",D="i6")
c<-data.frame(A=3,B=9,C=10,D=6)
d<-data.frame(A=3,B=9,C=10,D=6)
e<-rbind(a,b,c,d)
print(e)
A B C D
1 3 9 10 6
2 i3 i9 i10 i6
3 3 9 10 6
4 3 9 10 6
I am trying to convert the data-frame so that the values in the second row so that they become the column names of the data-frame, so the following is yielded:
print(f)
i3 i9 i10 i6
1 3 9 10 6
3 3 9 10 6
4 3 9 10 6
I have written the following:
f<-e[-2,]
colnames(f)<-e[2,]
Which seems to work for this small data-frame; however, for larger data-frames it does not seem to work properly. For example, the following is a snippet of a larger data-frame:
print(results2t)
V1 V2 V3
analysisID 118 118 118
Node 20 20 20
Dependent_Variable i1 i1 i1
Item b1 b17 i10
Overall_B_value -.03 .04 -.17
Overall_Std.Error .04 .08 .05
I have run the following:
results2t2<-results2t[-4,]
colnames(results2t2)<-results2t["Item",]
and also
colnames(results2t2)<-results2t["Item",]
and neither work (I am trying to get the values in the "Item" row to be the column names), as I am getting 13 for all the column names:
print(results2t2)
13 13 13
analysisID 118 118 118
Node 20 20 20
Dependent_Variable i1 i1 i1
Overall_B_value -.03 .04 -.17
Overall_Std.Error .04 .08 .05
Any thoughts?
The following works for me:
#make sure you use unlist to convert the data.frame to a vector containing
#the wanted names
colnames(results) <- unlist(results[row.names(results)=='Item',])
#remove the unneeded row
results <- results[!row.names(results)=='Item',]
Output:
> results
b1 b17 i10
analysisID 118 118 118
Node 20 20 20
Dependent_Variable i1 i1 i1
Overall_B_value -.03 .04 -.17
Overall_Std.Error .04 .08 .05
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With