[英]Make new Levels of categorical variable in new Variable Column in R
I am a newbee to R so got stuck here.. I have a categorical data我是 R 的新手,所以被困在这里.. 我有一个分类数据
levels(df$SO)
"SO1", "SO2","SO3","SO4","SO5","SO6",SO7",SO8"
I want to re-categorize these levels as follows BUT SAVE THEM AS NEW COLUMN (df$newSO) IN SAME DATAFRAME.我想将这些级别重新分类如下,但在同一数据框中将它们另存为新列 (df$newSO)。
levels(df$newSO)
"Unknown", "Known","Disease","Control"
Here Unknown
is made of SO1 and SO2 levels, Known
consists of SO3 and SO4.这里
Unknown
由 SO1 和 SO2 水平组成, Known
由 SO3 和 SO4 组成。 Disease
contains SO5,SO6 and SO7. Disease
含有 SO5、SO6 和 SO7。 Control
contains S8. Control
包含 S8。 I am using following我正在使用以下
levels(df$SC)[levels(df$SC)%in%c("SOC1","SOC2")] <- "Unknown"
But it is renaming the levels in same column (df$SO).但它正在重命名同一列中的级别 (df$SO)。 I want previous column intact while creating new column of new levels.
在创建新级别的新列时,我希望上一列完好无损。 How to do this in R?
如何在 R 中做到这一点?
您可以尝试以下操作
df$newSO <- ifelse(df$SO %in% c("SOC1", "SOC2"), "Unknown", "Known")
dplyr
and forcats
solution: dplyr
和forcats
解决方案:
library(dplyr)
library(forcats)
example <- data.frame(SO = factor(c("SO1", "SO2", "SO3", "SO4",
"SO5", "SO6", "SO7", "SO8")))
result <- example %>%
mutate(newSO = fct_collapse(SO,
Unknown = c("SO1", "SO2"),
Known = c("SO3", "SO4"),
Disease = c("SO5", "SO6", "SO7"),
Control = "SO8"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.