[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.
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]]
More information about the R-help
mailing list