Home » excel » r – Change values in row based on a column value and replacing specified column range

r – Change values in row based on a column value and replacing specified column range

Posted by: admin April 23, 2020 Leave a comment

Questions:

I found most of my answer with : Change values in row based on a column value r . There are two differences: I want to replace values based on test of a categorical variable and I want to specify the range for which I want the values to be replaced. I am working with a data frame of 8600 odd rows and 170 columns.

Here’s an example:-

x = data.frame(c("Jan", "Feb", "March", "April"), 
               c(9,3,4,6), c(8, 12,9,11), c(10, 9, 7, 0.6))
names(x) = c("Month","VAR1","VAR2", "VAR3")

I want to replace all the values of VAR2 and VAR3 (not VAR1) where month is “March” or “April” with NA.

I tried: x[x$Month==c("March", "April"), ] <- data.frame('x', NA, 3:4) but I get the error

Warning message:
In `[<-.factor`(`*tmp*`, iseq, value = c(1L, 1L)) :
  invalid factor level, NA generated

and print(x) gives:

  Month VAR1 VAR2 VAR3
1   Jan    9    8   10
2   Feb    3   12    9
3  <NA>   NA    3    1
4  <NA>   NA    4    1

There is some obvious programming beginner syntactical error I am unable to get past!

How to&Answers:

Try:

x[x$Month %in% c("March", "April"), c("VAR2", "VAR3")] = NA