I have a df with three columns: name, test and value. They describe chemical reaction measurements over somebody.
df <- data.frame(name=c("A","A","B","C","C","D"),
test=c("urea","creat","urea","urea","creat","creat"),
value=c(30,1,40,50,2,0.6))
> df
name test value
1 A urea 30.0
2 A creat 1.0
3 B urea 40.0
4 C urea 50.0
5 C creat 2.0
6 D creat 0.6
I need to group or filter only values with both urea or creat test, or equal paired names so df could became:
name test value
1 A urea 30.0
2 A creat 1.0
3 C urea 50.0
4 C creat 2.0
This is a solution i´ve worked on, but it doesn´t really works.
ndf <- data.frame()
n<-6
while(n>0){
ifelse(df[n,2]=="creat" && df[n-1,2]=="urea",
n<-n-2
ndf <- add_row(ndf, df[(n-1):n,2]),
n<-n-1)
}
Is there any "tidy" way to group or filter by pairs? maybe row_wise?
I think this is what you want. By each name
group, it keeps only groups where the total number of "urea"
values is equal to the total number of "creat"
values in the test
column.
library(dplyr)
df |>
filter(sum(test == "urea") == sum(test == "creat"), .by = name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With