2016-08-06 56 views
0

我已经问了一个类似的问题here,但似乎无法使它适用于类似的情况。用带有变量实例号的字符串求和实例

我有一个列中的数据帧,如(三个独立行):

There is some stuff here 
There are 25 per hpf 
There are 34 per hpf and there are 22 per hpf 
There are between 23 per hpf, 12 per hpf and 15 per hpf 

我想提取到一个单独的列中的最大数的一个数是否存在之前“每高倍视野”

我一直希望用下面这样做:

EoEDx$HPF<-sapply(EoEDx$HPF, function(x) 
    sum(rollapply(as.numeric(str_extract_all(x, '[0-9]+per hpf')[[1]]), 3, by = 1, prod))) 

,但我不断收到错误:

Error during wrapup: wrong sign in 'by' argument 

我想知道这是因为我预先指定了要添加的数字的数量 - 也是如何获得最大值而不是总和?

+0

你想* *金额或*提取*? –

+0

如果以下解决方案有效,请考虑接受它。 – akrun

回答

1

我们可以尝试

sum(rollapply(unlist(sapply(str_extract_all(df1$HPF, "[0-9]+(?= per hpf)"), 
        as.numeric)), 3, by = 1, prod)) 
#[1] 46116 

对于提取数量最多

as.numeric(sapply(str_extract_all(df1$HPF, "[0-9]+(?= per hpf)"), 
      function(x) x[which.max(as.numeric(x))][1])) 
#[1] NA 25 34 23