Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace values in one dataframe with values from another dataframe using index in R

I have to dataframes, which is called node_list and sup. Node_list consists of ID and loca2, which looks lile

ID loca2
1 A
2 B
3 C

and sup looks like

ID To
1 2
2 1
3 1

and I wish to replace the ID and to in sup by loca2 in node_list, which looks like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ID To
A B
B A
C A

how should i make it by R?
thanks a lot!!! 🙂

to be honest i have no idea how to achieve this and chatgpt is horrible on this so i’m left with no choice!

>Solution :

A simple solution would be to make node_list$loca2 into a named vector and call this as a replacement for each column:

library(tidyverse)

node_list <- tibble(ID = 1:3,
       loca2 = LETTERS[1:3])

names(node_list$loca2) <- node_list$ID

sup <- tibble(ID = 1:3, To = c(2, 1, 1))

sup |> 
  mutate(ID = node_list$loca2[as.character(ID)],
         To = node_list$loca2[as.character(To)])
#> # A tibble: 3 Ă— 2
#>   ID    To   
#>   <chr> <chr>
#> 1 A     B    
#> 2 B     A    
#> 3 C     A
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading