【发布时间】:2017-09-13 23:52:20
【问题描述】:
我正在尝试解析包含字符串以提取最大值(数字)的数据框,但遇到了一些麻烦。
如果我从这样的小标题开始:
tester <- tibble("phyloP46way_primate" = c(".{9}", "0.055{1}0.064{3}", "0.225{1}", "0.271{1}", "-0.706{1}-0.708{1}0.248{3}0.298{3}"))
然后使用map() 或modify() 应用str_match_all() 从每个字符向量中挑选出值,我得到一个带有5 个观察值(每个字符矩阵列表)的小标题(modify())由对 str_match_all() 的 5 次调用返回)(或包含 5 个字符矩阵列表的 1 列表(对于 map())。
regex ≤- "(?:(?:-?\\d+\\.?\\d+?)|\\.)(?=(?:\\{\\d+\\}|;|$))"
> str(foo_tbl<- tester %>% modify(str_match_all, pattern = regex))
Classes 'tbl_df', 'tbl' and 'data.frame': 5 obs. of 1 variable:
$ phyloP46way_primate:List of 5
..$ : chr [1, 1] "."
..$ : chr [1:2, 1] "0.055" "0.064"
..$ : chr [1, 1] "0.225"
..$ : chr [1, 1] "0.271"
..$ : chr [1:4, 1] "-0.706" "-0.708" "0.248" "0.298"
> str(foo_list<- tester %>% map(str_match_all, pattern = regex))
List of 1
$ phyloP46way_primate:List of 5
..$ : chr [1, 1] "."
..$ : chr [1:2, 1] "0.055" "0.064"
..$ : chr [1, 1] "0.225"
..$ : chr [1, 1] "0.271"
..$ : chr [1:4, 1] "-0.706" "-0.708" "0.248" "0.298"
现在,我想要做的是对这些“行”中的每一行应用一个函数。但是当我尝试映射时,它似乎只是将它们全部连接到一个向量中,并且只从整个批次中选择单个最大值,而不是一个/行:
> map(foo_tbl, function(x) list_to_max(x))
$phyloP46way_primate
$phyloP46way_primate[[1]]
[1] "0.298"
除非我在foo_tbl[[1]]而不是foo_tbl上做一些奇怪的索引和映射:
map(foo_tbl[[1]], function(x) list_to_max(x)) %>% unlist()
[1] "." "0.064" "0.225" "0.271" "0.298"
我认为我的list_to_max() 一定是在做意想不到的事情,因为这些行为符合我的预期:
> invisible(map(foo_tbl, function(x) print(paste0("x is: ", x))))
[1] "x is: ."
[2] "x is: c(\"0.055\", \"0.064\")"
[3] "x is: 0.225"
[4] "x is: 0.271"
[5] "x is: c(\"-0.706\", \"-0.708\", \"0.248\", \"0.298\")"
> invisible(modify(foo_tbl, function(x) print(paste0("x is: ", x))))
[1] "x is: ."
[2] "x is: c(\"0.055\", \"0.064\")"
[3] "x is: 0.225"
[4] "x is: 0.271"
[5] "x is: c(\"-0.706\", \"-0.708\", \"0.248\", \"0.298\")"
这是我的功能:
list_to_max <- function(character_vector) {
numbers <- suppressWarnings(as.numeric(character_vector))
if (all(is.na(numbers))) {
return(".")
} else {
numbers %>% max(., na.rm = TRUE) %>% toString()
}
}
【问题讨论】:
标签: r dplyr tidyverse stringr purrr