Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert row values into column names in r

Tags:

dataframe

r

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?

like image 213
costebk08 Avatar asked Sep 14 '15 13:09

costebk08


1 Answers

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
like image 151
LyzandeR Avatar answered Sep 30 '22 10:09

LyzandeR