How to convert row index number or row index name of an R data frame to a vector?

R ProgrammingServer Side ProgrammingProgramming

We might want to extract row index irrespective of its type (whether numeric or string) to do some calculations if it is incorrectly set as a row index. It happens during the data collection process or incorrect processing of data. Also, since row indexes are helpful to access row we must have proper names to them instead of values that might makes confusion. For example, if a data frame has row indexes as 43, 94, etc. then it might be confusing. Therefore, we should convert row indexes to a vector or a column if required.

Example

Consider the below data frame (Here, we are using simple sequence of numbers) −

> set.seed(1)
> x1<-rnorm(20,0.01)
> x2<-rpois(20,2)
> x3<-runif(20,2,5)
> df<-data.frame(x1,x2,x3)
> df
    x1 x2           x3
1  -0.616453811 3 4.738628
2   0.193643324 2 2.880810
3  -0.825628612 3 3.377197
4   1.605280802 2 2.997184
5   0.339507772 2 3.952611
6  -0.810468384 3 2.774050
7   0.497429052 0 3.435636
8   0.748324705 2 4.298932
9   0.585781352 3 2.252741
10 -0.295388387 3 4.625964
11  1.521781168 2 3.017219
12  0.399843236 4 4.518321
13 -0.611240581 2 3.040050
14 -2.204699887 1 3.001325
15  1.134930918 0 3.429054
16 -0.034933609 0 4.676595
17 -0.006190263 1 4.593018
18  0.953836211 2 3.169969
19  0.831221195 2 4.331962
20  0.603901321 2 4.881854

Converting row index number to a vector −

> Numeric_Vector_of_row_names<-as.numeric(rownames(df))
> Numeric_Vector_of_row_names
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
> is.vector(Numeric_Vector_of_row_names)
[1] TRUE

Now suppose that the row index was not a number as shown below −

> rownames(df)<-LETTERS[1:20]
> df
    x1 x2        x3
A -0.616453811 3 4.738628
B  0.193643324 2 2.880810
C -0.825628612 3 3.377197
D  1.605280802 2 2.997184
E  0.339507772 2 3.952611
F -0.810468384 3 2.774050
G  0.497429052 0 3.435636
H  0.748324705 2 4.298932
I  0.585781352 3 2.252741
J -0.295388387 3 4.625964
K  1.521781168 2 3.017219
L  0.399843236 4 4.518321
M -0.611240581 2 3.040050
N -2.204699887 1 3.001325
O  1.134930918 0 3.429054
P -0.034933609 0 4.676595
Q -0.006190263 1 4.593018
R  0.953836211 2 3.169969
S  0.831221195 2 4.331962
T  0.603901321 2 4.881854

These row indexes can be converted to a vector as shown below −

> Row_names_String<-rownames(df)
> Row_names_String
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
[20] "T"
> is.vector(Row_names_String)
[1] TRUE
raja
Published on 12-Aug-2020 13:04:00
Advertisements