[R] treating integer(0) and NULL in conditions and loops

Jan Kacaba jan.kacaba at gmail.com
Fri Mar 11 15:55:55 CET 2016

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.


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){

if (nchar(a[i])+nchar(rz))<6){

if (nchar(rz)+nchar(a[i+1]>6){

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:

if (length(nchar(rz))==0){z=0}
if (length(nchar(rz))>0){z=nchar(rz)}

Is it correct way of doing this or is there a better way without the need
of redefining new function?

	[[alternative HTML version deleted]]

More information about the R-help mailing list