One of the hardest things to remember when using R compared to other programming languages, is that almost everything you do is a vector operation. When you do q <- 0, R is going to apply the "<- 0" to the entire vector of q. And if you haven't created q before this, q will just be set equal to either 0 or 1. What you're asking R to do is if *any* value in socscore is less or equal to than 3, assign 0 to q, otherwise assign 1 to q. I'm assuming you want q to be a vector of 0's and 1's corresponding to whether socscore <= 3 or not?

There are a couple ways to do that. You can either use a loop:

Code:

q <- rep(NA, length(socscore))
for ( i in 1:length(socscore) {
if ( socscore[i] <= 3 )
q[i] <- 0
else
q[i] <- 1
}

You need to use the * to tell R which element of socscore and q you're talking about, otherwise it'll assume you mean the entire vector of both.*

But in general it's better to use vector operations in R rather than loops. The easier way to do this is:

Code:

q <- as.numeric(socscore > 3)

Here (socscore > 3) will result in a vector of booleans (true or false) of whether each element is greater than 3 or not and as.numeric() coerces the booleans to numerics as 0 or 1. Not again that any operation here applies to the whole vector. R will always operate on the whole vector unless you specifically ask for a particular index.

Again, I suggest not using attach(), but do data$socscore where data is whatever data.frame you read it into... but you'll eventually learn that on your own anyway if you keep using it, unless you stick to very simple stuff.