Index Names and lapply Function in R

Index Names and lapply Function in R,  This post, will show you how to use list indices in R’s FUN argument of the lapply function.

The application of the lapply function will be demonstrated in this article.

Example Data Generation

For this R tutorial, we’ll utilize the following data as a starting point.

List <- list(X= 10:15, Y= 1:5, Z= LETTERS[1:5])
List                        
$X
[1] 10 11 12 13 14 15

$Y
[1] 1 2 3 4 5

$Z
[1] "A" "B" "C" "D" "E"

Our sample list, as you can see from the previous RStudio console output, comprises three list members with the names X, Y, and Z. A vector object is contained in each of these list components.

Example: lapply() with seq_along() function

When using the lapply function in R, the following R programming code demonstrates how to handle list index names.

To accomplish this, we must use the seq_along function on our list and specify a user-defined function that accesses the list index names and values.

We may practically define whatever we want within this method. In the example below, we’re directing the function to return a phrase including the names of each list member and their values.

Index Names and lapply Function in R

lapply(seq_along(List),
       function(i) paste("The List Number Starting From",
                         i,
                         "with",
                         names(my_list)[[i]],
                         "contains the values",
                         paste(my_list[[i]], collapse = ", ")))
[[1]]
[1] "The List Number Starting From 1 with X contains the values 10, 11, 12, 13, 14, 15"

[[2]]
[1] "The List Number Starting From 2 with Y contains the values 1, 2, 3, 4, 5"

[[3]]
[1] "The List Number Starting From 3 with Z contains the values A, B, C, D, E".

As you can see, we’ve generated a list output in which each list member corresponds to a sentence in our input list.

How to find dataset differences in R Quickly Compare Datasets » finnstats

You may also like...

Leave a Reply

Your email address will not be published.

error

Subscribe Now