簡體   English   中英

如何從 2 個二進制變量創建具有 3 個級別的新分類變量?

[英]How can I create a new categorical variable with 3 levels from 2 binary variables?

EC <- data.frame(id=c(1,2,3,4,5,6,7,8,9), past_smoking=c("1","0","0","0","1","0","0","0","0"),current_smoking=c("0","1","1","1","0","1","1","1","0"))

EC

  id past_smoking current_smoking
1  1            1               0
2  2            0               1
3  3            0               1
4  4            0               1
5  5            1               0
6  6            0               1
7  7            0               1
8  8            0               1
9  9            0               0

到一個具有 3 個級別的新分類變量(0=no_Smoking,1=past_Smoking,2=current_Smoking?)謝謝你的幫助我在 R 編程中很新

我們可以使用case_when來分類到新的類別,即當 'past_Smoking' 為 1 時返回 1,當 current_Smoking 為 1 時,返回 2 否則為 '0'

library(dplyr)
EC %>%
   mutate(categ = case_when(past_smoking =='1' ~ '1',
         current_smoking == '1' ~ '2', TRUE ~ '0'))

或如@user20650 所述

EC %>%
    type.convert(as.is = TRUE) %>%
    mutate(categ = current_smoking + !past_smoking)
# your data
EC <- data.frame(id=c(1,2,3,4,5,6,7,8,9), past_smoking=c("1","0","0","0","1","0","0","0","0"),current_smoking=c("0","1","1","1","0","1","1","1","0"))

# create new column
EC_new <- EC %>% 
  mutate(newvar=case_when(past_smoking==0 & current_smoking==0 ~ 0,
                          past_smoking==1 ~ 1,
                          current_smoking==1 ~ 2))

# make a factor variable
EC_new$newvar <- factor(EC_new$newvar, levels = c(0,1,2),
         labels = c("no_smoking", "past_smoking", "current_smoking"))

也許你可以試試下面的代碼

transform(
  type.convert(EC, as.is = TRUE),
  newvar = past_smoking + 2 * current_smoking
)

這使

  id past_smoking current_smoking new
1  1            1               0   1
2  2            0               1   2
3  3            0               1   2
4  4            0               1   2
5  5            1               0   1
6  6            0               1   2
7  7            0               1   2
8  8            0               1   2
9  9            0               0   0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM