Dans dataframe df (trié par colonne deux), je dois sélectionner la première ligne une où deux> 7 et extraire ses données de la colonne quatre:
[3,] 3 8 11 18
En gros, j'ai besoin de cette ligne:
one two three four [1,] 1 6 11 16 [2,] 2 7 12 17 [3,] 3 8 11 18 [4,] 4 9 11 19 [5,] 5 10 15 20
4 Réponses :
Voici une option utilisant which.max
df <-read.table(text =
"one two three four
1 6 11 16
2 7 12 17
3 8 11 18
4 9 11 19
5 10 15 20", header = T)
df[which.max(df$two > 7), ] # one two three four #3 3 8 11 18
Une ligne en supposant que votre data.frame s'appelle df
df[head(which(df$two > 7), 1), ]
Si vous avez besoin de plus d'une ligne du haut, mettez simplement à jour ce 1 code> à n'importe quel nombre.
Vous pouvez utiliser le package sqldf . Si le nom du bloc de données est df :
library(sqldf)
result <- sqldf("SELECT * FROM df
WHERE two > 7
ORDER BY two
LIMIT 1")
Vous pouvez utiliser le package tidyverse
one two three four 1 3 8 11 18
Sortie:
d<-data.frame(c(1,2,3,4,5),
c(6,7,8,9,10),
c(11,12,11,11,15),
c(16,17,18,19,20))
d<-`colnames<-`(d,c('one','two','three','four'))
library(dplyr)
d%>%
arrange(two)%>%
filter(two>7)%>%
head(1)