In dataframe df (sorted by column two), I need to select first one row where two > 7 and extract its data from column four:
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
Basically i need this row:
[3,] 3 8 11 18
Here is an option using which.max
df[which.max(df$two > 7), ]
# one two three four
#3 3 8 11 18
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)
One liner assuming your data.frame is called df
df[head(which(df$two > 7), 1), ]
In case you need more than one top rows, just update that 1
to any number.
You can use sqldf
package. If the name of the data frame is df
:
library(sqldf)
result <- sqldf("SELECT * FROM df
WHERE two > 7
ORDER BY two
LIMIT 1")
You can use tidyverse package
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)
Output:
one two three four
1 3 8 11 18
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.