-4

I would like to conditionally replace the values of each columns in R. My data looks like below image.

Initial Data

In this, I want to check if the values are >UCL then want to replace with UCL value and If the values are

The Output should look like below image:

Result Image

Like this I have many rows and columns data and I'm looking for solution in R.

Vinay
  • 75
  • 1
  • 8
  • Add dataset example with `dput` please: `dput(head(mydata))`. – Artem Klevtsov Dec 01 '15 at 10:26
  • Welcome to StackOverflow! Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you. – David Arenburg Dec 01 '15 at 10:41

1 Answers1

0

We create a 'df2' as a copy of 'df1'. Using the 'i1' and 'i2' index, we replace the columns 1:4 in 'df2' with corresponding 'UCL' and 'ICL' values that fits the condition.

df2 <- df1
i1 <- df1[1:4] > df1$UCL
i2 <- df1[1:4] < df1$LCL
df2[1:4][i1] <- df2$UCL[row(df2[1:4])][i1]
df2[1:4][i2] <- df2$LCL[row(df2[1:4])][i2]
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thank You, It works fine.... In your code, I just have to replace the column numbers in place of 4 right? – Vinay Dec 01 '15 at 10:58
  • @Vinay Yes, you can replace that with the relevant columns or use `df2[grep('^M', names(df2))]` – akrun Dec 01 '15 at 12:36