[R] some question about vector[-NULL]

Duncan Murdoch murdoch.duncan at gmail.com
Wed Sep 10 12:45:59 CEST 2014


On 10/09/2014, 3:21 AM, PO SU wrote:
> 
> Dear expeRts,
>       I have some programming questions about NULL in R.There are listed as follows:
> 1. I find i can't let a list have a element NULL:
> a<-list()
> a$ress<-1
> a$res<-NULL
> a
> str(a)

You can do it using

a <- list(ress = 1, res = NULL)

> How can i know i have a named element but it is NULL, not just get a$xxxx,a$iiii,a$oooo there all get NULL

That's a little harder.  There are a few ways:

"res" %in% names(a) & is.null(a[["res"]])

or

identical(a["res"], list(res = NULL))

or

is.null(a[[2]])

should all work.

Generally because of the special handling needed, it's a bad idea to try
to store NULL in a list.

> 2.The most important thing:
> a<-1:10
> b<-NULL or 1
> a<-c(a,b) will work so i don't need to know whether b is null or not,but:
> a[-NULL] can't work!!  i just need a[-NULL]==a , how can i reach this purpose?

Using !, and a logical test, e.g.

a[!nullentry(a)]

where nullentry() is a function based on one of the tests above, but
applied to all entries.

Duncan Murdoch



More information about the R-help mailing list