I need to find the number of the row that data in the columns reached a certain value.
Data:
Data = data.frame( Time = seq(1,5),
V1 = c(0.1, 0.2, 0.4, 0.7, 0.9),
v2 = c(0.1, 0.12, 0.41, 0.72, 0.91),
v3 = c(0.03, 0.13, 0.62, 0.50, 0.90))
Desired result: (First Time In 0.6)
V1 V2 V3
1 4 4 3
CodePudding user response:
We can use dplyr with summarise
and first(which(condition))
library(dplyr)
Data %>% summarise(across(-Time, ~first(which(.x>0.6))))
V1 v2 v3
1 4 4 3
Or with base R:
data.frame(lapply(Data[-1], \(x) first(which(x>0.6))))
CodePudding user response:
Using base R:
Use which
to find the indices of rows that satisfy your condition and min
to find the lowest (i.e., first) of these indices. Also use lapply
to apply it multiple columns like so:
data.frame(lapply(Data[c("V1", "v2", "v3")], function(x) min(which(x > 0.6))))