Hi,

On Nov 3, 2009, at 9:56 AM, Joel Fürstenberg-Hägg wrote:

Hi all,

I'm trying to write a script that changes all negative values in a data frame column to a small positive value, based on the the minimum value of the column.

However, I get the following error:

Error in if (x[i] < 0) { : argument is of length zero

This is telling you that x[i] is a zero length object, so you're indexing is wrong

As well, I would "minimum" to be the smallest of the non-negative values...

Aa_non_neg=(fieldTrial0809$Aa) # Copy column from data frame to manipulate

nonNegative = function(x)
{
  minimum=min(x) # Should only use positive minimum!

You have to tell R to only use positive numbers, min(x[x > 0]) would have worked.

I'm not really sure what you're looping over below.

  for (i in x)
  {

     if(x[i]<0) # Found a negative value
     {
        x[i]=minimum/10 # Change to a new non-negative value
     }
  }
}

This will work over each column of an "orig.df" data.frame (assumes all cols are numeric) and generate the new data.frame you're looking for:

new.df <- as.data.frame(apply(orig.df, 2, function(col) {
  min.val <- min(col[col > 0])
  col[col < 0] <- min.val
  col
}))

-steve

--
Steve Lianoglou
Graduate Student: Computational Systems Biology
  |  Memorial Sloan-Kettering Cancer Center
  |  Weill Medical College of Cornell University
Contact Info: http://cbio.mskcc.org/~lianos/contact

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to