r语言 - 根据条件提取数据帧中的数字,并确定这些数字在哪些行和数字中



给定一个数据帧:

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
#   ...       ...      ...

我们可以用meltsubset

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

或者如果你喜欢tidyverse

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

最诚挚的问候,汉斯

最新更新