0

The matrix I have looks something like this:

Plot   A  B  C  

 1     1  0  0

 2     1  0  1

 3     1  1  0

And I have a dataframe that looks like this

A  5
B  4
C  2 

What I would like to do is replace the "1" values in the matrix with the corresponding values in the dataframe, like this:

Plot   A  B  C  

 1     5  0  0

 2     5  0  2

 3     5  4  0

Any suggestions on how to do this in R? Thank you!

1 Answer 1

1

An option with tidyverse

library(dplyr)
df1 %>%
    mutate(across(all_of(df2$col1),
    ~ replace(.x, .x== 1, df2$col2[match(cur_column(), df2$col1)])))

-output

 Plot A B C
1    1 5 0 0
2    2 5 0 2
3    3 5 4 0

data

df1 <- structure(list(Plot = 1:3, A = c(1L, 1L, 1L), B = c(0L, 0L, 1L
), C = c(0L, 1L, 0L)), class = "data.frame", row.names = c(NA, 
-3L))

df2 <- structure(list(col1 = c("A", "B", "C"), col2 = c(5, 4, 2)), 
class = "data.frame", row.names = c(NA, 
-3L))
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, that seems like it should work. However, I get an error that the columns "don't exist" even though they certainly do in both dataframes. Is the issue that they need to be in the same order and of the same length? Because currently they are not. Error is " ! Can't subset columns that don't exist."
@hmich77 If you check the df2 with col1 in my post, it gives the same values you showed. Your example didn't show the column names, so i used col1, col2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.