简体   繁体   English

从计数到案例 R

[英]From count to cases in R

I have a dataset with a column which indicate the number of occurence of a group constituted by multiples variables.我有一个数据集,其中有一列指示由多个变量构成的组的出现次数。 Here SEX and COLOR .这里SEXCOLOR

CASES <- base::data.frame(SEX   = c("M", "M", "F", "F", "F"), 
                          COLOR = c("brown", "blue", "brown", "brown", "brown"))
COUNT <- base::as.data.frame(base::table(CASES))
COUNT

I need to change the structure of the dataset, so I have one row for each occurence of the group.我需要更改数据集的结构,因此该组的每次出现都有一行。 Someone helped me to create a function which works perfectly.有人帮助我创建了一个完美运行的 function。

countsToCases <- function(x, countcol = "Freq") {
    # Get the row indices to pull from x
    idx <- rep.int(seq_len(nrow(x)), x[[countcol]])
    # Drop count column
    x[[countcol]] <- NULL
    # Get the rows from x
    x[idx, ]
}

CASES <- countsToCases(base::as.data.frame(COUNT))
CASES

The problem is now that I have a HUGE dataset (the babyname dataset from tidytuesday), and this is not working since it's too slow.现在的问题是我有一个巨大的数据集(来自 tidytuesday 的babyname数据集),而且它不起作用,因为它太慢了。

db_babynames <- data.table::as.data.table(tuesdata$babyname)

db_babynames <- db_babynames[
  j = characters_n := stringr::str_count(string  = name,
                                         pattern = ".")
][
  j = c("year", "characters_n", "n")
]

I'm looking for a faster solution, working with the data.table package if possible.我正在寻找一个更快的解决方案,如果可能的话,使用data.table package。

If an uncounted version is needed I would use tidyr::uncount() , but consider the recommendation in this post to work with your original data如果需要未计数的版本,我会使用tidyr::uncount() ,但请考虑这篇文章中的建议以使用您的原始数据

library(dplyr)
library(tidyr)

CASES <- base::data.frame(
  SEX   = c("M", "M", "F", "F", "F"),
  COLOR = c("brown", "blue", "brown", "brown", "brown")
  )

COUNT <- count(CASES, SEX, COLOR, name = 'Freq')

tidyr::uncount(base::as.data.frame(COUNT), Freq)
#>   SEX COLOR
#> 1   F brown
#> 2   F brown
#> 3   F brown
#> 4   M  blue
#> 5   M brown

Created on 2022-03-25 by the reprex package (v2.0.1)reprex package (v2.0.1) 创建于 2022-03-25

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM