Sample data:
df <- data.frame(bucket = c("A", "B", "C", "D"),
apples = c("<4", "U", "22", "9"),
oranges = c("U", "<4", "15", "7"),
bananas = c("8", "6", "16", "<4"),
pears = c("U", "7", "<4", "10"))
My desired output:
bucket apples oranges bananas pears
1 A <4 U 8 U
2 B U <4 6 7
3 C 22 U 16 <4
4 D 9 U <4 10
The idea is I am trying to replace the lowest number value with the letter "U" in each row. Also note I am treating the 'bucket column' as having non-unique rows.
However, there are a few exceptions to this;
- If the row has more than 1 instance of "<4", then don't change anything in the row.
- If the row already has at least 1 instance of "U", then don't change anything in the row.
What I have tried:
for(i in 1:nrow(df)){
if(sum(df[i,] == "U") > 0 || sum(df[i,] == "<4") > 1){
next
} else {
df <- df %>%
rowwise() %>%
mutate(across(everything(),
~replace(.x, which.min(.x), "U")))
}
}
As a primarily tidyverse user, I can't seem to understand how to use rowwise with mutate and across properly.
A tidyverse solution would be awesome, but will happily take other solutions.