# choose minimum value and insert it into certain row

Hi there!

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
``````
1 Like

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 
#>   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
``````

Created on 2021-08-13 by the reprex package (v2.0.0)

1 Like

Thank you so much, StatSteph!
It is a simple and clear answer code!

A base alternative

``````outcome <- as.numeric(c(6,7,"NA",8,3,"NA",8,4,"NA"))
#> Warning: NAs introduced by coercion
outcome[which(is.na(outcome))] <-
pmin(outcome[!is.na(outcome)][c(T,F)],outcome[!is.na(outcome)][c(F,T)])
outcome
#>  6 7 6 8 3 3 8 4 4
``````

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.