这是另一个问题的后续问题,R Question - Trying to use separate to split data with a non-constant delimiter
[直到后来我才意识到我还有其他问题,请多多包涵,谢谢!
[作为参保年龄组的示例,我想将其划分为成人,青少年和儿童,以便每个事件都给出每个年龄组参与者的人数。我正在尝试对年龄和性别做同样的事,然后将其与整个数据集联系起来进行预测。让我知道是否需要更多详细信息。
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
我尝试使用下面的方法,但是它只给出了一个庞大的向量。
字符串
x
期望的结果
Incident Child Teen Adult Female Male
1 0 0 1 1 0
2 0 0 2 0 2
stri_count()
。我对性别变量也应用了相同的步骤。最后,我将两个结果与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