Mcgroger
Mcgroger

Reputation: 67

Replacing numeric elements by equal index

I have a big dataframe dim(13265x40). The dataframe was created by combining several seperate dataframes in a list by: big_dataframe = bind_rows(dataframe_list, .id = "Index"). .id = "Index" gave me an additional column called "Index" with a numeric input (1, 2, 3, 4, etc.) so I still can identify the seperate dataframes in the big_dataframe.

Example:

big_dataframe:
Index  A  B  C  D
1      3  6  7  1
1      6  6  2  0
1      7  5  4  2
2      4  0  7  4
2      3  2  9  1
2      9  4  4  5
3      7  1  5  2
3      3  9  3  4
3      1  1  2  10
4      10 6  7  1

and so on. Then i have an indexlist: indexlist = c("John", "Peter", "Michael", "Brian", etc.) which contains "character" elements.

The goal would be, to replace the numeric input in big_dataframe$Index by the element of indexlist with the equal index. Example:

big_dataframe:
Index  A  B  C  D
John   3  6  7  1
John   6  6  2  0
John   7  5  4  2
Peter  4  0  7  4
Peter  3  2  9  1
Peter  9  4  4  5
Peter  7  1  5  2
Peter  3  9  3  4
Peter  1  1  2  10
Brian  10 6  7  1

I am a bit lost for this an don't know how I could approach this problem.

Thank you in advance

Upvotes: 1

Views: 33

Answers (1)

akrun
akrun

Reputation: 887691

If the 'index' is numeric and as it is starting from 1, it can be used as a index of replacing the values with 'indexlist' value in the same order

big_dataframe$Index <- indexlist[big_dataframe$Index]

data

big_dataframe <- structure(list(Index = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 
4L), A = c(3L, 6L, 7L, 4L, 3L, 9L, 7L, 3L, 1L, 10L), B = c(6L, 
6L, 5L, 0L, 2L, 4L, 1L, 9L, 1L, 6L), C = c(7L, 2L, 4L, 7L, 9L, 
4L, 5L, 3L, 2L, 7L), D = c(1L, 0L, 2L, 4L, 1L, 5L, 2L, 4L, 10L, 
1L)), class = "data.frame", row.names = c(NA, -10L))

indexlist <- c("John", "Peter", "Michael", "Brian")

Upvotes: 2

Related Questions