kaiyu wei
kaiyu wei

Reputation: 517

declaration of variables in R

I have a problem of using a variable in R Studio. My code is as following. "child_birth" is a vector composed of 49703 strings that indicates some information about the birth of childre. What I did here is to tell whether the last 7 characters in each element of the vector is "at home". So I used a for loop and an if statement. if it is "at home", then the corresponding element in vector "GetValue" will be TRUE.

forloop <- (1:49703)
for (i in forloop){
  temp <- child_birth[i]
  if (substr(temp, nchar(temp)-6, nchar(temp)) == "at home" ) {
    GetValue[i] = TRUE
  }
  else{ GetValue[i] = FALSE }
}

I googled it to make sure that in R I don't need to do a predecalration before using a variable. but when I ran the code above, I got the error information:" Error: object 'GetValue' not found". So what's the problem with it?

Thank you!

Upvotes: 1

Views: 128

Answers (1)

John Coleman
John Coleman

Reputation: 51978

GetValue[i] only makes sense if GetValue (and i) exist. Compare: x+i only makes sense if x and i exist, which has nothing to do with whether or not x and i must be declared before being used.

In this case, you need to define GetValue before the loop. I recommend

GetValue <- logical(length(child_birth))

so as to allocate enough space. In this case, you could drop the else clause completely since the default logical value is FALSE.

I also recommend dropping the variable forloop and using

for(i in seq_along(child_birth))

Why hard-wire in the magic number 49703? Such numbers are subject to change. If you put them explicitly in the code, you are setting yourself up for future bugs.

Upvotes: 2

Related Questions