Alex
Alex

Reputation: 51

Rename multiple values of multiple columns in a data frame in r(rename file number by filename)

I have a dataframe that gives the file numbers. But I would like to change the file numbers with filenames that I have in another vector/matrix. How can do it in r?

I am giving a reproducible matrix below:

> ash<-data.frame(matrix(c(4,2,NA,9,3,8,NA,NA,1,5,6,7),nrow=3, byrow=TRUE))
> ash2<-matrix(c("jegjgqe","hdd","odew","dhjs","ddj","hdiwhek","dij","jsosaeo"))
> ash
  X1 X2 X3 X4
1  4  2 NA  9
2  3  8 NA NA
3  1  5  6  7

What I want is a matrix where the file number will be replaced by the names of ash2 matrix/vector. Like the value 1 would be "jegjgqe", value 2 would be "hdd" and so on. Is there any way to replace all values with those names at once?

Upvotes: 0

Views: 241

Answers (1)

akrun
akrun

Reputation: 887148

We can use the indexing on a vector/matrix (matrix is a vector with dim attributes

ash[] <-  ash2[as.matrix(ash)]

-output

ash
       X1      X2      X3   X4
1    dhjs     hdd    <NA> <NA>
2    odew jsosaeo    <NA> <NA>
3 jegjgqe     ddj hdiwhek  dij

Or use lapply to loop over the columns of the data.frame and replace the values based on the index to 'ash2' values

ash[] <- lapply(ash, function(x) ash2[x])

Upvotes: 1

Related Questions