[R] Searching and deleting elements of list

Bojanowski, M.J. (Michal) M.J.Bojanowski at uu.nl
Thu Mar 8 15:59:14 CET 2007


Hi,

A little bit shorter perhaps:

> # deletion
> mydata2 <- lapply( mydata, function(x) x[ !(x %in% A) ] )
> # insert A again
> mydata2[[1]] <- A
> mydata2
[[1]]
[1] "aaa" "bbb" "ccc" "ddd" "eee"

[[2]]
[1] "vvv" "ooo" "zzz"

[[3]]
[1] "sss" "jjj" "ppp"

[[4]]
character(0)


Please note that if all elements are deleted (as in 'mydata2[[4]]') you
get 'character(0)' instead of 'NULL'.
You could fix that by

lapply(mydata2, function(x) if(identical(x, character(0))) NULL )

or by (recomennded):

f <- function(x) # perform replacements etc.
{
	rval <- x[ !(x %in% A) ]
	if ( identical(rval, character(0)) )
		return(NULL)
	else return(rval)
}
mydata2 <- lapply( mydata, f ) # apply
mydata2[[1]] <- A # insert A
mydata2


PS. Powodzenia! :)




*** Note that my e-mail address has changed to m.j.bojanowski at uu.nl
*** Please update you address books accordingly. Thank you!

_________________________________________
Michal Bojanowski
ICS / Sociology
Utrecht University
Heidelberglaan 2; 3584 CS Utrecht
Room 1428
m.j.bojanowski at uu.nl
http://www.fss.uu.nl/soc/bojanowski
-----Original Message-----
From: r-help-bounces at stat.math.ethz.ch
[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of jastar
Sent: Thursday, March 08, 2007 12:31 PM
To: r-help at stat.math.ethz.ch
Subject: [R] Searching and deleting elements of list


Hi,
I have a problem. Please, look at example and try to help me!!

> A<-c("aaa","bbb","ccc","ddd","eee")
> B<-c("vvv","ooo","aaa","eee","zzz","bbb")
> C<-c("sss","jjj","ppp","ddd")
> D<-c("bbb","ccc")
>mydata=list(A,B,C,D)

I want to find and delete from 'mydata' all elements which occur in A
(except A). 
I mean after "operation":
> mydata[[1]]
[1] "aaa" "bbb" "ccc" "ddd" "eee"
> mydata[[2]]
[1] "vvv" "ooo" "zzz"
> mydata[[3]]
[1] "sss","jjj","ppp"
> mydata[[4]]
NULL

My list have about 10000 subelements (each contains several strings) so
using loops is senseless.

Thank's for all replies and sorry for my English (I hope you understand
what I'm talking about) :-)
 
--
View this message in context:
http://www.nabble.com/Searching-and-deleting-elements-of-list-tf3368489.
html#a9372270
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
R-help at stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list