Your answer and for loops are fine, the only problem being that it would run slow with a lot of data because it's not vectorized. When you have a lot of simple conditionals like this it's generally more compact and readable to use a switch/case statement, such as the functions switch or case_when in R. These methods are usually vectorized too.
Example data.
df <- structure(list(Units = c("not_measured", "ug/L", "ng/L", "Other"
), Other = c(NA, NA, NA, "pg/ml"), Score = c(NA, NA, 5, NA),
Score2 = c(NA, 29.9, NA, 11.3)), class = "data.frame", row.names = c(NA,
-4L))
> df
Units Other Score Score2
1 not_measured <NA> NA NA
2 ug/L <NA> NA 29.9
3 ng/L <NA> 5 NA
4 Other pg/ml NA 11.3
Using mutate and case_when from dplyr.
library("dplyr")
df <- df %>%
mutate(score_ugl=case_when(
Units == "ug/L" ~ Score2,
Units == "ng/L" ~ Score * 0.001,
Units == "Other" & Other == "pg/ml" ~ Score2 * 0.001
))
> df
Units Other Score Score2 score_ugl
1 not_measured <NA> NA NA NA
2 ug/L <NA> NA 29.9 29.9000
3 ng/L <NA> 5 NA 0.0050
4 Other pg/ml NA 11.3 0.0113
Could you please give us some representative data to work with?
Can you not see the data in the post? This is representative of the dataset... ! Values have been changed, but otherwise this is a snapshot of what I'm working with. Blank lines need to be retained because there are other (unshown) columns with values in. Dataset is over 1000 columns, so can't possibly share. I'm only showing the relevant bits.
Apologies. Is that completely representative? Are there any aspects to the data that isn't addressed by the example in your OP?
For what I need it is completely representative. If it helps, you can assume every row has a unique ID. Otherwise it is unfortunately what I'm dealing with as the output!
To share your data, please paste in the results of
dput(head(data))into your original question. Thanks.