如何解决这个问题:过滤器,R 中的 grep?

How to solve this problem: filter, grep in R?

嘿,伙计们 我有这个:


df<-data.frame(x1=c("0.25","0.4**","0.24"),
           x2 = c("","0.72***","0.68*"),
           x3 = c("","","0.75"))
rownames(df) <- c("X2","X3","X4")
df %>% 
  rownames_to_column() %>% 
  gather(key, values,-rowname) %>% 
  filter(values %in% "[*]")

ouput:
<0 linhas> (ou row.names de comprimento 0)

预期输出:

select 只有“重要”值 * ** *** ****

# rowname key values
2 X3 x1 0.4**
5 X3 x2 0.72***
6 X4 x2 0.68*

您可以使用带有字符 class 的正则表达式来执行此操作:

df<-data.frame(x1=c("0.25","0.4**","0.24"),
               x2 = c("","0.72***","0.68*"),
               x3 = c("","","0.75"))
rownames(df) <- c("X2","X3","X4")
df %>% 
  rownames_to_column() %>% 
  gather(key, values,-rowname) %>% 
  filter(values %>% str_detect("[*]"))

使用 %in% 进行整个字符串匹配,使用正则表达式匹配查询字符串的一部分。