2016-11-13 76 views
0

如果有一个数据帧:提取号码,并确定哪些行和数字,这些数字在

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 

如何选择其值大于5的数字?以及如何确定哪些行和列是这些数字?也就是说,我怎么得到这样一个数据帧:

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

尝试用'which'即'i1 <- which(df > 5,arr.ind = TRUE); data.frame(rownames = rownames(df)[i1 [,1]],colnames = colnames(df)[i1 [,2]],value = df [i1])或library(reshape2); subset (as.matrix(df)),值> 5)' – akrun

回答

2

我们可以使用meltsubset

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

或者如果你喜欢tidyverse,

library(tidyverse) 
    df %>% 
    rownames_to_column() %>% 
    gather(colname,value,-rowname) %>% 
    filter(value > 5) 

最好的问候,
Hans

相关问题