R 问题 - 非常量定界符并将其绑定回数据框

R Question - Non-Constant Delimiter and tying it back into the data frame

这是另一个问题的后续问题,

后来才知道问题比较多,还请多多包涵,谢谢!

作为 participation_age_group 的示例,我想将其分为成人、青少年和儿童,以便每个事件都给出每个年龄组参与者的数量。我正在尝试对年龄和性别做同样的事情,然后将其与整个数据集联系起来进行预测。如果您需要更多详细信息,请告诉我。

dput(head(x[, c(1, 3)]))    structure(list(incident=c(1,2),age_group= c("0::Adult 18+", "0::Adult 18+||1::Adult 18+"), participant_gender = c("0::Female","0::Male||1::Male")),.Names = c("incident","participant_age_group","participant_gender"),row.names = c(NA, 2L), class = "data.frame")

如果需要更多数据, Sample Data from the dataset

我尝试使用下面的方法,但它只给出了一个大向量。

字符串 <- c("Child 0-11","Teen 12-17","Adult 18+")

x <- str_count(字符串,x$participant_age_group)

期望的结果

Incident Child Teen Adult Female Male
   1       0    0    1      1     0
   2       0    0    2      0     2

我根据你的图片创建了一个样本。我不知道你有多少年龄段。如果你有很多,你必须做一些不同的事情。但是这里有三个类别。我用它们创建了一个向量。我使用 stri_count() 在带有 sapply() 的循环中使用向量。我也对性别变量应用了相同的程序。最后,我将两个结果合并为 bind_cols().

library(tidyverse)
library(stringi)

so <- tibble(id = 1:4,
             participant_age_group = c("0::Adult 18+", 
                                       NA,
                                       "0::Child 0-11||1::Teen 12-17",
                                       "0::Adult 18+||1::Adult 18+"),
             participant_gender = c("0::Female",
                                    NA,
                                    "0::Female||1::Female",
                                    "0::Male||1::Female"))

# Create a vector with the three target categories.
category <- c("Child 0-11", "Teen 12-17", "Adult 18+")
gender <- c("Female",  "Male")

sapply(category,function(x){
  stri_count_regex(so$participant_age_group, x)
}) %>% 
as_tibble -> result1

sapply(gender,function(x){
stri_count_regex(so$participant_gender, x)
}) %>% 
as_tibble -> result2

bind_cols(result1, result2)

# A tibble: 4 x 5
#  `Child 0-11` `Teen 12-17` `Adult 18+` Female  Male
#         <int>        <int>       <int>  <int> <int>
#1            0            0           1      1     0
#2           NA           NA          NA     NA    NA
#3            1            1           0      2     0
#4            0            0           2      1     1