[R] Replace column values in R conditional on values from different column

GradStudentDD dd7kc at virginia.edu
Sat Oct 13 20:59:44 CEST 2012

Dear List,

I am working on a stats project and have been stumped by the issue of
replacing values in a column conditional on values from a different column.
I searched the forum and google in general, and was able to put some code
together, but it's not working the way it's supposed to... I appreciate any
help you can offer! A detailed description of the issue, and the code I came
up with, is below. 

I am trying to separate one variable (CohenSum) into separate values for
males and females, in two separate columns, so I can do computations on them
(i.e. mean, sd). I tried the code below, but the values I got didn't make
sense - the length of the M and F columns should have been about half of the
initial column length and NA for the rest (I have about half men and half
women in the sample) but instead every cell has values in it, except for the
initial NAs. I think R somehow inserted 0 instead of NAs for the gender
values which were not supposed to be in that column (i.e. replaced values
for females with 0 in the male column) but I don't know why. 


for(i in 1:length(Health2$CohenSum)){
  if (Health2$q_5a[i]==1) Health2$CohenM[i] <- Health2$CohenSum[i]
  else if (Health2$q_5a[i]==2) Health2$CohenF[i] <- Health2$CohenSum[i]
  else Health2$CohenF[i] <- NA

View this message in context: http://r.789695.n4.nabble.com/Replace-column-values-in-R-conditional-on-values-from-different-column-tp4646087.html
Sent from the R help mailing list archive at Nabble.com.

More information about the R-help mailing list