[R] Is there a better way to check if an element of a list exists than using match on names?

jim holtman jholtman at gmail.com
Wed Jul 30 03:26:20 CEST 2008


Is this what you want:

> "var3" %in% names(ipf)
[1] FALSE
> "var1" %in% names(ipf)
[1] TRUE
>


On Tue, Jul 29, 2008 at 6:20 PM,  <Paul.Rustomji at csiro.au> wrote:
>
> Hello R mailing list
>
> Is there a better way than this to see if an element exists *within* a
> list object :
>
> #generate "file.txt" using current routine
> cat("var1=33\nvar2=TRUE",file="file.txt")
>
> #load file to a list called "ipf"
> f <- function(.file){source(.file,local=TRUE);as.list(environment())}
> ipf<- f("file.txt")
>
> print(ipf)
>
>
> #this is the bit I need help with...
> res <- match("var1",names(ipf)) # returns result > 0 if "var" exists
> within ipf ie. TRUE
> print(res)
> res <- match("var3",names(ipf)) #returns NA as "var3" is not in ipf ie.
> FALSE
> print(res)
>
> I have tried the exists function but cannot get it to apply to items of
> a list (though can get it to see if the list exists as an object...)
>
> Thanks
> Paul.
>
> Paul Rustomji
> Rivers and Estuaries
> CSIRO Land and Water
> GPO Box 1666
> Canberra ACT 2601
>
> ph +61 2 6246 5810
> mobile 0406 375 739
>
> ______________________________________________
> R-help at r-project.org 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.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?



More information about the R-help mailing list