Yuzhuo Wang Yuzhuo Wang - 25 days ago 7
R Question

Extract numbers in a data frame by conditions and determine which rows and numbers are these numbers in

Given a data frame:

df=data.frame(co1=c(5,9,6,1,6),co2=c(8,5,4,6,2),co3=c(6,5,4,1,2),co4=c(6,1,5,3,2),co5=c(5,1,2,6,8))
rownames(df)=c('row1','row2','row3','row4','row5')
df
# co1 co2 co3 co4 co5
#row1 5 8 6 6 5
#row2 9 5 5 1 1
#row3 6 4 4 5 2
#row4 1 6 1 3 6
#row5 6 2 2 2 8


How can I select numbers whose values are greater than 5? And how to determine which row and column are these numbers in? That is, how do I get a data frame like this:

# rownames colnames value
# row1 col2 8
# row1 col3 6
# row1 col4 6
# row2 col1 9
# row3 col1 6
# ... ... ...

Answer

We can use melt with subset

library(reshape2)
subset(melt(as.matrix(df)), value>5)