[R] treating integer(0) and NULL in conditions and loops
William Dunlap
wdunlap at tibco.com
Fri Mar 11 18:27:17 CET 2016
I would suggesting using "" instead of NULL for rz, throughout this code.
(I would also suggest making sure the code can be copied into R without
causing a syntax error before posting the request for help.)
Bill Dunlap
TIBCO Software
wdunlap tibco.com
On Fri, Mar 11, 2016 at 9:10 AM, Adams, Jean <jvadams at usgs.gov> wrote:
> To reframe the problem ... the issue is not with the function nchar() (or
> whatever), it's with the input value rz being null. I suggest you build
> into the loop whatever actions/outputs you want when rz is NULL.
>
> for (i in 1:10){
> if (is.null(rz)) {
> # do something here
> } else {
> if (nchar(rz)>6) {
> # ...
> }
> if (nchar(a[i])+nchar(rz))<6) {
> # ...
> }
> if (nchar(rz)+nchar(a[i+1]>6) {
> # ...
> }
> }
> }
>
> Jean
>
>
> On Fri, Mar 11, 2016 at 8:55 AM, Jan Kacaba <jan.kacaba at gmail.com> wrote:
>
> > Hello, I have following problem in loops. It occurred to me multiple
> times
> > bellow is an example. Inside if() I have sometimes function f(x) which
> may
> > return integer(0). If I test f(x)>1 and f(x)=integer(0) I get error.
> Maybe
> > it can be solved more eloquently without loop or swithces. I don't know.
> >
> > Example:
> >
> > a=c("ab","abc","abcd","abcde","abcdefghjk") # vector from which new
> strings
> > will be constructed
> > svec=NULL # vector of string
> > rz=NULL # string
> >
> > for (i in 1:10){
> > if (nchar(rz)>6){
> > svec[i]=rz
> > rz=NULL
> > }
> >
> > if (nchar(a[i])+nchar(rz))<6){
> > rz=paste(rz,a[i])
> > }
> >
> > if (nchar(rz)+nchar(a[i+1]>6){
> > svec[i]=rz
> > rz=NULL
> > }
> > }
> >
> > I'm not interested how to treat nchar() function in particular but
> general
> > function. One solution which comes to mind is to redefine function for
> > example nchar() function like this:
> >
> > new.nchar=function(x){
> > if (length(nchar(rz))==0){z=0}
> > if (length(nchar(rz))>0){z=nchar(rz)}
> > return(z)
> > }
> >
> > Is it correct way of doing this or is there a better way without the need
> > of redefining new function?
> > <derek>
> >
> > [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> > 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.
> >
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.
>
[[alternative HTML version deleted]]
More information about the R-help
mailing list