r - How to add multiple numeric values in a single cell of a large list in R
问题描述
Hi I want to calculate the sum of product quantity against a shipment_id. I have dataframe with two columns.
shipment_id details
XYQWE13 [{"orderid"=1,"quantity"=>2},{"orderid"=2,"quantity"=>1}]
UYTDW54 [{"orderid"=1,"quantity"=>5},{"orderid"=2,"quantity"=>5}]
SKFEF32 [{"orderid"=1,"quantity"=>2},{"orderid"=2,"quantity"=>1},{"orderid"=3,"quantity"=>5}]
So I will have to fetch the numeric value only after the quantity part. I tried this to extract quantity and the number against it
y <- stringr::str_extract_all(string = raw_data_shipment2$details, pattern = '"quantity"=>[0-99]+')
Which gave me a large list
Name Type Value
y list(3) List of length 3
[[1]] character [1] '"quantity"=>2''"quantity"=>1'
[[2]] character [1] '"quantity"=>5''"quantity"=>5'
[[2]] character [1] '"quantity"=>2''"quantity"=>1''"quantity"=>5'
Further using this
y2 <- stringr::str_extract_all(string = y, pattern = '=>[0-99]+')
y3 <- stringr::str_extract_all(string = y2, pattern = '[0-99]+')
Gave me this result of this large list
Name Type Value
y3 list(3) List of length 3
[[1]] character [1] '2''1'
[[2]] character [1] '5''5'
[[2]] character [1] '2''1''5'
Now I wanted to sum the numeric part and was hoping I could cbind it with my original dataframe. But I'm stuck on how to sum it. Any help would be highly appreciated.
解决方案
因为您正在使用stringr
我将假设您正在使用其他tidyverse
包 - 特别是purrr
. 如果您是,您应该能够使用 map 函数对 y1、y2、y3 等进行求和:
z1 <- purrr::map(y1, ~sum(as.numeric(.)))
z2 <- purrr::map(y2, ~sum(as.numeric(.)))
z3 <- purrr::map(y3, ~sum(as.numeric(.)))
然后你可以绑定 z1、z2、z3 等。
推荐阅读
- dataframe - 使用 XLSX.gettable 读取非连续列?
- c++ - SFINAE - 如果参数是可复制构造的,则启用一个函数,否则启用另一个函数
- java - 遍历map的时候顺序是怎么决定的
- c# - 在 C# 中获得奇怪的价值
- javascript - jsPDF:将创建的 pdf 直接打印到打印机设备
- java - 第一个控制器中第二个控制器的访问方法和标签
- python - 如何确定图像是主要是黑色还是主要是白色
- javascript - React-select multi select 在未选择任何值时更新道具
- python - Python API 错误 - 'faultstring': 'JSONThreatProtection
- c++ - 使用 c++ 和 windows API 在 windows 上更改输入法