r - 如何减去列表中的连续数字
问题描述
我在数据框中有一些文本如下
输入
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"
然后我怎样才能减去这两个数字(以获得正输出)
解决方案
正如@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
推荐阅读
- go - 如何迭代golang模板中的一系列数字?
- javascript - 单击时Vue切换按钮的颜色和文本
- c++ - 在 std::thread 构造函数中调用派生类的函数最终调用基类的函数
- mongodb - 错误:MongoDB:未知版本:mountain_lion
- flutter - 如何从无状态父窗口小部件调用有状态子窗口小部件的状态函数?
- roku - 如何修改 ROKU 中的字幕位置?
- c++ - 如何通过Qdialog中的qtablewidget填充作为MainWindow成员的qvector
- c# - 给定的 ColumnMapping 与大量数据的源或目标中的任何列都不匹配
- autohotkey - 除应用程序外,AutoHotKey 无法重新映射
- arrays - 如何使用静态文本创建数组