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
| 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