1

I'd like to change the values in a data.frame that match a criteria, but I'd like to specify the criteria only applies to certain columns. I'm aware about:

  • Being df = Dataframe: df[df < 0] = 0. This applies to all elements in all the columns, so that, this not resolve my problem
  • Being df = Dataframe and Col: a dataframe's column: df$Col[df$Col < 0] = 0.This applies to all elements in 1 column, so that, this not resolve my problem neither.

Which is the solution in the middle that allows me to filter all elements for those specified columns that I define?

Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
Rafa
  • 2,879
  • 2
  • 21
  • 27
  • Something like `df$oneColumn[df$anotherColumn < 0 & dfonemoreColumn < 0] <- 0` ? – juba Apr 04 '13 at 07:45
  • That would help in case of few columns, the problem is I need to do it for all the df's columns (750), except one. – Rafa Apr 04 '13 at 08:00
  • Could you please provide a reproducible example ? – juba Apr 04 '13 at 08:01
  • Any data.frame that comes with R with a large number of columns would help. In case you would like to modify all the columns of the df except one of them, I can figure out to use a for loop to do it, however I don't give up and want to find a more elegant solution. – Rafa Apr 04 '13 at 08:10
  • 3
    Please give sample data or reproducible example so that good people here can help you better. See http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – CHP Apr 04 '13 at 08:10
  • Thanks for your help. The key thing that resolve the problem was what e4e5f4 answered: the use of [,cols] is what you can use to define where in the data.frame the criteria should be applied. Thanks – Rafa Apr 04 '13 at 10:39

2 Answers2

2

Assuming that specific columns are available as indices:

cols <- 1:750
df[,cols][df[,cols] < 0] = 0

If you need to exclude some columns, use negative index, for ex:

cols <- c(-3,-4)
Nishanth
  • 6,932
  • 5
  • 26
  • 38
  • Thanks e4e5f4, but it didn't work,new.df has different columns than df. see example: – Rafa Apr 04 '13 at 08:49
0

To exclude some columns you can use negative index even as

cols <- -c(3,4)

Ram
  • 1