I just have a quick question about choosing the minimum value. As you can see from the dataset there are three names (i.e., A, B, and C). A and B have a certain value in Outcome while C has no value. And I want to choose the minimum value between A and B and insert the value into C. I have three separate trials (i.e., trial1, trial2, trial3). Please help to make the code!
Thank you!
Best,
# create dataframe
data <- data.frame(
name=c("A", "B", "C", "A", "B", "C", "A", "B", "C"),
trial=c("trial1", "trial1", "trial1", "trial2", "trial2", "trial2",
"trial3", "trial3", "trial3"),
outcome=c(6,7,"NA",8,3,"NA",8,4,"NA")
)
data
name trial outcome
1 A trial1 6
2 B trial1 7
3 C trial1 NA
4 A trial2 8
5 B trial2 3
6 C trial2 NA
7 A trial3 8
8 B trial3 4
9 C trial3 NA
Thanks for the good reproducible example and clear question. A very good post!
I'd suggest using the tidyverse to help out by grouping by trial and then replacing any outcome when name="C" with the minimum of the outcome as follows:
data <- data.frame(
name=c("A", "B", "C", "A", "B", "C", "A", "B", "C"),
trial=c("trial1", "trial1", "trial1", "trial2", "trial2", "trial2",
"trial3", "trial3", "trial3"),
outcome=c(6,7,"NA",8,3,"NA",8,4,"NA")
)
library(tidyverse)
data %>%
group_by(trial) %>%
mutate(
outcome=if_else(name=="C", min(outcome, na.rm=TRUE), outcome)
)
#> # A tibble: 9 x 3
#> # Groups: trial [3]
#> name trial outcome
#> <chr> <chr> <chr>
#> 1 A trial1 6
#> 2 B trial1 7
#> 3 C trial1 6
#> 4 A trial2 8
#> 5 B trial2 3
#> 6 C trial2 3
#> 7 A trial3 8
#> 8 B trial3 4
#> 9 C trial3 4