1

I got this df with some ranks (1 for the biggest number, 2 for second one...):

Rank.Df = data.frame(A1 = c(1, NA, NA),
                     A2 = c(2, 1, NA),
                     A3 = c(2, 1 , 3)); Rank.Df

And I got a vector with the corresponding numbers:

Values = c(50,40,30) #50 is the value for rank 1, 40 is for rank 2 and 30 is for rank 3

But I'm trying do replace the ranking dataframe with the values in the vector. I can even do that, but in a slow way:

# First I created another data frame to store the data
Df.results = data.frame(A1 = NA,
                        A2 = NA,
                        A3 = NA) 

# And then loop through all combinations between rows and columns    
for(i in 1:nrow(Rank.Df)) {
  for(k in 1:ncol(Rank.Df)) {
    Df.results[i,k] = Values[Rank.Df[i,k]] 
  }
}

I imagine there is a smarter way to perform this operation, I just don't know how.

zx8754
  • 52,746
  • 12
  • 114
  • 209
Bryan Souza
  • 497
  • 2
  • 10

1 Answers1

2

No need for loops here. Instead, you can change the data frame into a matrix and the whole operation will be vectorized:

Df.results <- Rank.Df
Df.results[] <- Values[as.matrix(Rank.Df)]

Df.results
#   A1 A2 A3
# 1 50 40 40
# 2 NA 50 50
# 3 NA NA 30
Robert Hacken
  • 3,878
  • 1
  • 13
  • 15