'Finding the smallest value in a list in R
I have the following list, which I extracted from a function that returns endless car values.I want to find the smallest speed value using R.
car1 <- c(12, 200, "red")
names(car1) <- c("speed", "distance", "color")
car2 <- c(31, 150, "grey")
names(car2) <- c("speed", "distance", "color")
car3 <- c(8, 100, "blue")
names(car3) <- c("speed", "distance", "color")
x<- list(car1, car2, car3)
x
[[1]]
speed distance color
"12" "200" "red"
[[2]]
speed distance color
"31" "150" "grey"
[[3]]
speed distance color
"8" "100" "blue"
Obviously in this example it is visible, but if we had data for 200 cars it wouldn't be. Or endless data that comes from a function. I tried different ways, like
min(x$speed)
min(x[i]$speed)
min(x[[i]]$speed)
and if conditions, but they didn't work. I would appreciate any help.
Solution 1:[1]
as.integer(sapply(x, `[[`, "speed"))
# [1] 12 31 8
which.min(as.integer(sapply(x, `[[`, "speed")))
# [1] 3
x[[ which.min(as.integer(sapply(x, `[[`, "speed"))) ]]
# speed distance color
# "8" "100" "blue"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | r2evans |
