mercredi 4 décembre 2019

Function for if then condition not working because of apparently not specified variable

I've got a dataset of a pilotstudy with a test with 12 items. I've created the variable: test1_processed as follows, which gives me the amount of items the person could solve:

for(i in 1:length(test1)){
  data[,test1[i]] <- ifelse(data[,test1[i]]<=0, 1, data[,test1[i]])
}
describe(data[,test1])
data$test1_processed <- ifelse(apply(is.na(data[,test1]), 1, all),NA,rowSums(data[,test1],na.rm=TRUE))

Now I want to create a new variable, which simple enough codes a "1" if test_processed=12 (if all items were solved) or a "0" if not.

I tried it like this:

data$test1_complete <- ifelse(apply(is.na(data$test1_processed), 1, all),NA,1)

but R said, that dim(x) had to be positive.

So I checked the variable:

is.vector(data[,"test1_processed"])
[1] TRUE
is.numeric(data[,"test1_processed"])
[1] TRUE

Then I tried it like this:

data$test1_complete <- ifelse(apply(is.na(data[,test1_processed]), 1, all),NA,1)

but R said that the object test1_processed could not be found, even though it is a column in the data set.

If I tried it like this:

test1_processed <- ifelse(apply(is.na(data[,test1]), 1, all),NA,rowSums(data[,test1],na.rm=TRUE))
data$test1_complete <- ifelse(apply(is.na(data[,test1_processed]), 1, all),NA,1)

it said that undefined columns were selected.

Something like this:

data$test1_complete <- if(test1_processed>11) 1 else 0
only returned: Error in if (test1_processed > 11) 1 else 0 : 
  missing value where TRUE/FALSE needed
In addition: Warning message:
In if (test1_processed > 11) 1 else 0 :
  the condition has length > 1 and only the first element will be used

I would be very glad, if somebody could help me out :)

Thanks!

Aucun commentaire:

Enregistrer un commentaire