首页 > 解决方案 > 如何减去列表中的连续数字

问题描述

我在数据框中有一些文本如下

输入

rownumber  CStage
1           38-40cm
2           27-22
3           32cm and 40cm

我想将每个数字中的两个数字相减,CStage输出为

期望的输出

rownumber  CStage
1           2
2           5
3           8

我用过stringr::str_extract_all(df$CStage,"\\d{2}")

这给了我一个列表,每个元素都包含两个数字

[[1]]
[1] "38" "40"

[[2]]
[1] "27" "22"

[[3]]
[1] "32" "40"

然后我怎样才能减去这两个数字(以获得正输出)

标签: r

解决方案


正如@Cath 在您可以使用的评论中提到的sapply,将其转换为数字并diff在它们之间取值。

num_list <- stringr::str_extract_all(df$CStage,"\\d{2}")
abs(sapply(num_list, function(x) diff(as.numeric(x))))
#[1] 2 5 8

推荐阅读