首页 > 解决方案 > 复制行 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))

标签: rrepeat

解决方案


一个选项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

推荐阅读