Home > Blockchain >  How do I change the value of one column in rows that have a specific value in a different column in
How do I change the value of one column in rows that have a specific value in a different column in

Time:02-02

Sorry if that was worded poorly. This is a data frame for chemical amounts in water samples. I have two columns (that are important in my question), one with the value of the reading and the other column has its units. Right now, some of the units are in milligrams and the others are in micrograms. I want to take every row that is in milligrams, multiply by 1000 so everything is in micrograms, and then I will have no need for the unit's column.

Screenshot of part of the data im looking at. Look at value and unit

I tried to:

fixit <- function(x){
  x*1000
}

fixit(df[df$units == 'mg/l',])

I also tried it with filters and using a for loop instead of the fixit function. Couldn't think of any other way to do it.

CodePudding user response:

You can use ifelse():

## create example data
set.seed(832479)
df = data.frame(value=runif(10), unit=sample(c("mg/l","ug/l"), 10, replace=T))

       value unit
1  0.3265564 mg/l
2  0.6617228 mg/l
3  0.3592905 mg/l
4  0.4203186 ug/l
5  0.8636146 ug/l
6  0.2278049 mg/l
7  0.3608057 ug/l
8  0.8555797 mg/l
9  0.6580872 ug/l
10 0.9925924 ug/l

## now do the conversion for the "mg/l" values
df$converted = ifelse(df$unit=="mg/l", df$value*1000, df$value)

       value unit   converted
1  0.3265564 mg/l 326.5563531
2  0.6617228 mg/l 661.7227946
3  0.3592905 mg/l 359.2905267
4  0.4203186 ug/l   0.4203186
5  0.8636146 ug/l   0.8636146
6  0.2278049 mg/l 227.8049409
7  0.3608057 ug/l   0.3608057
8  0.8555797 mg/l 855.5796870
9  0.6580872 ug/l   0.6580872
10 0.9925924 ug/l   0.9925924

Is that what you were after?

CodePudding user response:

We may need to subset the value with a logical index and apply the fixit function on the subset

i1 <- df$units == 'mg/l'
df$value[i1] <- fixit(df$value[i1])
  • Related