rannoudanames rannoudanames - 1 month ago 10
R Question

R, for loop on data frame column and need value from an other

I have the following type of data frame:

Gender FSIQ VIQ PIQ Weight Height MRIcount IQindicator
1 Female 133 132 124 118 64.5 816932 1
2 Male 140 150 124 NA 72.5 1001121 1
3 Male 139 123 150 143 73.3 1038437 1
4 Male 133 129 128 172 68.8 965353 1
5 Female 137 132 134 147 65.0 951545 1
6 Female 99 90 110 146 69.0 928799 0


My objective is to make 2 vectors, one with the MRIcount of which the IQindicator is 1 and the other for IQindicator is 0

I have written the following:

MRI_low <-c()
MRI_high <- c()
for (index in brain_data[,8]){
if (index = 1){
MRI_high <- append(MRI_high, MRIcount)
} else {
MRI_low <- append(MRI_low, MRIcount)
}
}


How can I make this work?

for this example i would need:


> MRI_low <-c(928799) MRI_high <-c(816932, 1001121, 1038437, 965353,
> 951545)


Answer

You can just use logical indexing. Assuming your data frame's name is df, one solution could be

MRI_high <- df$MRIcount[df$IQindicator == 1]
MRI_low  <- df$MRIcount[df$IQindicator == 0]

With the $-operator, you can access/extract on variable of your data frame. Then, you see the logical condition in brackets. This makes a vector consisting of TRUE where the stated condition holds and FALSE if it does not hold. If you index a vector with a logical vector, you keep the values with a TRUE.