Convert row values ​​to column names in r

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 a 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 given:

print(f)
  i3 i9 i10 i6
1  3  9  10  6
3  3  9  10  6
4  3  9  10  6

I wrote the following:

f<-e[-2,]
colnames(f)<-e[2,]

Which seems to work for this small data frame; however, for large frames of data, it does not seem to work properly. For example, the following fragment 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 ran the following:

results2t2<-results2t[-4,]
colnames(results2t2)<-results2t["Item",]

as well as

colnames(results2t2)<-results2t["Item",]

and it doesn't work (I'm trying to get the values ​​in the "Item" row as column names), since I get 13 for all 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?

+4
source share
2 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
+3

unlist:

colnames(results2t2)<-unlist(results2t["Item",])
results2t2
#                      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
+2

Source: https://habr.com/ru/post/1607282/


All Articles