Salomé Friry
Salomé Friry

Reputation: 11

Finding specific elements in lists

I am stuck at one of the challenges proposed in a tutorial I am reading.

# Using the following code:

challenge_list <- list(words = c("alpha", "beta", "gamma"),

numbers = 1:10

letter = letters

# challenge_list

# Extract the following things:
#
# - The word "gamma"

# - The letters "a", "e", "i", "o", and "u"

# - The numbers less than or equal to 3

I have tried using the followings:

## 1
challenge_list$"gamma"

## 2
challenge_list [[1]["gamma"]]

But nothing works.

Upvotes: 0

Views: 43

Answers (3)

akrun
akrun

Reputation: 886948

We can use a function and then do the subset if it is numeric or not and then use Map to pass the list to vector that correspond to the original list element and apply the f1. This would return the new list with the filtered values

f1 <- function(x, y) if(is.numeric(x)) x[ x <= y] else x [x %in% y]
out <- Map(f1, challenge_list, list('gamma', 3, c("a","e","i","o","u")))
out

-output

#$words
#[1] "gamma"

#$numbers
#[1] 1 2 3

#$letter
#[1] "a" "e" "i" "o" "u"

Upvotes: 0

Duck
Duck

Reputation: 39595

Try this. Most of R objects can be filtered using brackets. In the case of lists you have to use a pair of them like [[]][] because the first one points to the object inside the list and the second one makes reference to the elements inside them. For vectors the task is easy as you only can use a pair of brackets and set conditions to extract elements. Here the code:

#Data
challenge_list <- list(words = c("alpha", "beta", "gamma"),
numbers = 1:10
letter = letters
#Code
challenge_list[[1]][1]
letter[letter %in% c("a", "e", "i", "o","u")]
numbers[numbers<=3]

As I have noticed your data is in a list, you can also play with the position of the elements like this:

#Data 2
challenge_list <- list(words = c("alpha", "beta", "gamma"),numbers = 1:10,letter = letters)
#Code 2
challenge_list[[1]][1]
challenge_list[[3]][challenge_list[[3]] %in% c("a", "e", "i", "o","u")]
challenge_list[[2]][challenge_list[[2]]<=3]

Output:

challenge_list[[1]][1]
[1] "alpha"
challenge_list[[3]][challenge_list[[3]] %in% c("a", "e", "i", "o","u")]
[1] "a" "e" "i" "o" "u"
challenge_list[[2]][challenge_list[[2]]<=3]
[1] 1 2 3

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 101064

> challenge_list$words[challenge_list$words == "gamma"]
[1] "gamma"

> challenge_list$letter[challenge_list$letter %in% c("a","e","i","o","u")]
[1] "a" "e" "i" "o" "u"

> challenge_list$numbers[challenge_list$numbers<=3]
[1] 1 2 3

Upvotes: 0

Related Questions