r - 复制行 n 次,其中 n 是字符串的值
问题描述
我有一个数据集,其中列出了各州及其各自城市,其中一些地方已汇总(不是由我汇总)并归类为"Other ([count of places])" (e.g. Other (99))
. 附加到此地点列表的是数值'count'
。我想 1.) 找到每个位置的平均计数和 2.) 根据括号内的数字复制这些“其他...”位置以及平均值。下面的例子:
set.seed(5)
df <- data.frame(state = c('A','B'), city = c('Other (3)','Other (2)'), count = c('250','50'))
输出:
状态 | 城市 | 数数 |
---|---|---|
一种 | 其他 (3) | 83.333 |
一种 | 其他 (3) | 83.333 |
一种 | 其他 (3) | 83.333 |
乙 | 其他 (2) | 25.000 |
乙 | 其他 (2) | 25.000 |
到目前为止,我只能弄清楚如何从括号中提取数字并创建一个平均值:
average = df$count/as.numeric(gsub(".*\\((.*)\\).*", "\\1", df$city))
解决方案
一个选项uncount
。用 提取“city”中的数字部分parse_number
,将“count”除以“n”并用复制行uncount
library(dplyr)
library(tidyr)
df %>%
mutate(n = readr::parse_number(city), count = as.numeric(count)/n) %>%
uncount(n)
-输出
state city count
1 A Other (3) 83.33333
2 A Other (3) 83.33333
3 A Other (3) 83.33333
4 B Other (2) 25.00000
5 B Other (2) 25.00000
推荐阅读
- reactjs - 从父组件触发子组件内部的函数
- asp.net - @{...} 中的代码是在表单提交时运行还是一直运行
- c++ - 使用 gmtime 和 mktime 在同一天生成两个 time_t 值,“函数可能不安全”错误
- python - 试图比较两个列表或一个相同的列表
- ruby-on-rails - 调试文件,以便在 Rails 上制作确认页面 ruby
- android - 可搜索微调器不搜索空间
- push-notification - 如何在 MFP 的推送通知中发送宣传图片
- asp.net - ASP 站点输入字符串的格式不正确。尝试上传图片后
- ios - 将数据从 containerView 传递到 MainViewControler
- sql - Postgres SQL选择第一个字母不是@或#的单词频率