-2

Say I have a list consisting of a range of integers from 1-10 with repetition and I want to remove all the 0s from that list, is there an easy way to go about doing that?

Something like na.omit but for my choice of elements?

zx8754
  • 52,746
  • 12
  • 114
  • 209
Qwertford
  • 1,039
  • 2
  • 14
  • 25
  • 1
    Reproducible example? – Sotos Jul 07 '16 at 11:44
  • `x[ x == 0 ] <- NA` then use na.omit. Or maybe `x[ x != 0 ]`. – zx8754 Jul 07 '16 at 11:44
  • @Laterow, I don't think it's a duplicate, since this question aims at subsetting a `list` – loki Jul 07 '16 at 11:53
  • @zx8754 what is this process called (x[ x == 0 ] <- NA), the use of square brackets and double equals, ive never seen anything like that before. – Qwertford Jul 07 '16 at 12:07
  • 1
    @Qwertford This is a combination of subsetting (`[`) and assignment (`<-`). It say assign all elements in the *vector* x that are to 0 the value NA (missing). Note that in R terminology, x is a *vector*, not a list. See ` help("[")` and help("<-") for more details. – lmo Jul 07 '16 at 12:14
  • 1
    Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you. – zx8754 Jul 07 '16 at 12:15

2 Answers2

1

since you did not provide an example I create a list ls

ls <- list(rep(0:10, 10))

lsnew <- ls[[1]][ls[[1]] != 0]

It should be mentioned that lsnew is a numeric vector, not a list!

This is a simple example of subsetting in R. For further information on subsetting different data structures refer to:

loki
  • 9,816
  • 7
  • 56
  • 82
  • which package is this a part of? I looked in help and couldn't find it. – Qwertford Jul 07 '16 at 12:04
  • This is base R. You don't need any packages for lists. Some details on subsetting [here](http://adv-r.had.co.nz/Subsetting.html) – loki Jul 07 '16 at 12:07
  • Where can I learn to use those square brackets? Ive never seen them before and dont understand. what you've written. – Qwertford Jul 07 '16 at 12:13
  • http://www.cookbook-r.com/Basics/Getting_a_subset_of_a_data_structure/ or http://www.cookbook-r.com/Basics/Indexing_into_a_data_structure/ – loki Jul 07 '16 at 12:16
1

extending @loki's answer you can also exclude more than one element

ls <- list(rep(0:10, 10))

#excluding 0
lsnew <- ls[[1]][which(ls[[1]] != 0)]

#excluding 0 & 1
lsnew <- ls[[1]][! ls[[1]] %in% c(0,1)]
Latrunculia
  • 696
  • 1
  • 7
  • 15
  • I ment generalising to the exclusion of more than one element. I edited my answer to reflect that `which` is not needed. – Latrunculia Jul 07 '16 at 12:21