首页 > 解决方案 > 在R中将一个变量拆分为两个新变量

问题描述

所以我在 R studio 中使用 ISwR 包中的数据集 bcmort。该数据集包含在引入筛查之前丹麦和其他地区的乳腺癌死亡信息。

我想要做的是获取队列变量(由 4 个级别组成)并将其拆分为变量“期间”和“区域”。

知道我会怎么做吗?

提前致谢

编辑:我认为如果显示队列水平可能会有所帮助: 在此处输入图像描述

四个层次分别是:研究组、国家研究组、历史研究组、历史国家研究组

标签: rsplit

解决方案


不知道您想要的输出是什么样子,这是一个使用dplyr和的函数的通用解决方案stringr。我可以从这四个因素水平猜测您可能希望如何构建新变量AreaPeriod,但我不知道我的方法是否是您想要的。

从我的快速检查来看,我猜你的Area变量是基于是否Cohort是“国家的”。我猜这个Period变量是基于是否Cohort是“历史的”。在这种情况下,我将使用str_detectfromstringr包来检测队列值中的模式。我将使用它mutate来创建新列。

library(ISwR)
library(dplyr)
library(stringr)

bcmort %>%
  mutate(Period = if_else(str_detect(cohort, "Hist"), "Historical", "Not historical")) %>%
  mutate(Area = if_else(str_detect(cohort, "Nat|nat"), "National", "Not national"))

     age        cohort bc.deaths    p.yr         Period         Area
1  50-54     Study gr.         9   64144 Not historical Not national
2  55-59     Study gr.        34   92734 Not historical Not national
3  60-64     Study gr.        43   83510 Not historical Not national
4  65-69     Study gr.        53   87408 Not historical Not national
5  70-74     Study gr.        56   77427 Not historical Not national
6  75-79     Study gr.        28   25600 Not historical Not national
7  50-54      Nat.ctr.        89  767111 Not historical     National
8  55-59      Nat.ctr.       434 1067778 Not historical     National
9  60-64      Nat.ctr.       516  906943 Not historical     National
10 65-69      Nat.ctr.       535  826254 Not historical     National
11 70-74      Nat.ctr.       545  635385 Not historical     National
12 75-79      Nat.ctr.       214  192946 Not historical     National
13 50-54     Hist.ctr.        22   57669     Historical Not national
14 55-59     Hist.ctr.        45  113143     Historical Not national
15 60-64     Hist.ctr.        82  139065     Historical Not national
16 65-69     Hist.ctr.       104  155697     Historical Not national
17 70-74     Hist.ctr.       128  128454     Historical Not national
18 75-79     Hist.ctr.        57   40196     Historical Not national
19 50-54 Hist.nat.ctr.       104  577528     Historical     National
20 55-59 Hist.nat.ctr.       443  931245     Historical     National
21 60-64 Hist.nat.ctr.       485  916923     Historical     National
22 65-69 Hist.nat.ctr.       491  838476     Historical     National
23 70-74 Hist.nat.ctr.       418  608008     Historical     National
24 75-79 Hist.nat.ctr.       182  182824     Historical     National

如果我猜错了,那么你可以适应你想要的输出。


推荐阅读