-3

I work in R and have List A and List B, in which list A <<< B. Both lists share the value of the entry of one column (chr.). I want to add a new column to list B based on entry of list A. I.e in list B, look at column xy for any shared values with list A at column zk, add a new column to list B with the values of list A of column p.

for(i in range(1:length(B[[y]]))){for(j in range(1:length(A[[x]]))){if(A[[x]] == B[[y]]){mutate(B, newvalue = A[[z))}}}
Fishpenis1
  • 25
  • 2
  • 2
    Can you please provide minimal reproducible sample data and matching expected output? That way it will be much easier for us to help because it gives us something to work with. At the moment your code is not reproducible because we have no idea how `A` and `B` look like. – Maurits Evers Jun 08 '19 at 09:10
  • 1
    If you need help with the reproducible example, see [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Roman Luštrik Jun 08 '19 at 09:15
  • I believe that you need the `merge` function. – G5W Jun 08 '19 at 11:55

1 Answers1

0

As @G5W indicated you can use merge function. At first you should convert your lists into the data frames then merge. After it you can convert the resulting data frame back into list.

Basically there is no need to implement the algorithm yourself using for loops. It is already done in base R. Please see the code below:

l1 <- list(x = 3:7, y = letters[3:7])
l2 <- list(x = 1:10, z = letters[1:10])
df1 <- as.data.frame(l1, stringsAsFactors = FALSE)
df2 <- as.data.frame(l2, stringsAsFactors = FALSE)
df_m <- merge(df1, df2)
l_m <- as.list(df_m)
l_m

Output:

$`x`
[1] 3 4 5 6 7

$y
[1] "c" "d" "e" "f" "g"

$z
[1] "c" "d" "e" "f" "g"
Artem
  • 3,304
  • 3
  • 18
  • 41