-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
  • 46,390
  • 10
  • 104
  • 180
Qwertford
  • 863
  • 2
  • 9
  • 21

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
  • 8,836
  • 6
  • 49
  • 76
  • 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
  • 686
  • 1
  • 6
  • 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