IlonaU
IlonaU

Reputation: 13

Finding characters from one list in other list [R]

Probably a basic question, but I am quite new to R and I am struggling a little bit with lists. I hope that some of you could help me. I tried to look online for a similar problem, but I could not find anything for exactly my case, sorry if I overlooked something.

I have two lists similar to this :

list1
$ `value1`
[1] "character1"

$ `value2`
[1] "character2"

$ `value3`
[1] "character1" "character3" "character4"


list2
$ `XX`
[1] "character1" "character3" "character6"

$ `YY`
[1] "character1" "character2" "character3"

$ `ZZ`
[1] "character3" "character4" "character5"

What I want to do it take subscript XX from the list2, find it in the list1 and output a new list with just these occurencies, which are in subscript XX of a list2. I do not want output TRUE/ FALSE, I want to get something like this:

final_list
$ `value1`
[1] "character1"

$ `value3`
[1] "character1" "character3"

I tried

list1[list2$XX]

which works if the values are integers, but not if they are characters. I am then getting out long list like this:

$<NA>
NULL

Any help really appreciated!!

Upvotes: 1

Views: 75

Answers (1)

Sven Hohenstein
Sven Hohenstein

Reputation: 81693

You can use this approach:

tmp <- lapply(list1, intersect, list2$XX)
final_list <- tmp[as.logical(sapply(tmp, length))]

# $value1
# [1] "character1"
#
# $value3
# [1] "character1" "character3"

In the first step, common strings are returned. In the second step, empty list elements are removed.

Upvotes: 1

Related Questions