Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select multiple elements from a list

Tags:

list

r

subset

I have a list in R some 10,000 elements long. Say I want to select only elements, 5, 7, and 9. I'm not sure how I would do that without a for loop.

I want to do something like mylist[[c(5,7,9]] but that doesn't work. I've also tried the lapply function but haven't been able to get that working either.

like image 877
user1357015 Avatar asked Aug 25 '12 03:08

user1357015


People also ask

How do you select multiple elements in a list?

To select multiple items in a list, hold down the Ctrl (PC) or Command (Mac) key. Then click on your desired items to select. All of the items you have selected should be highlighted with a different-colored background. Note: Be sure to hold the Ctrl (PC) or Command (Mac) key down while selecting multiple items.

How do you select multiple items from a list in Python?

You can also pick multiple items in a list. In this example, we call on our variable, list1, and the items zero through two. Python pulls the first and second items only. The brackets' semicolon tells python to pull items in the list from the first noted number (zero) to the last number but exempt it(three).

How do you select all elements in a list?

To select elements from a Python list, we will use list. append(). We will create a list of indices to be accessed and the loop is used to iterate through this index list to access the specified element. And then we add these elements to the new list using an index.

How do I select a specific element in a list in R?

The list() function is used to create lists in R programming. We can use the [[index]] function to select an element in a list. The value inside the double square bracket represents the position of the item in a list we want to extract.


1 Answers

mylist[c(5,7,9)] should do it.

You want the sublists returned as sublists of the result list; you don't use [[]] (or rather, the function is [[) for that -- as Dason mentions in comments, [[ grabs the element.

like image 140
Glen_b Avatar answered Oct 13 '22 00:10

Glen_b