有条件地将因子水平分为两个不同的水平

时间:2018-06-05 13:41:14

标签: r forcats

我有一个数据框,例如:

df <- data.frame(
        type = c("BND", "INV", "BND", "DEL", "TRA"),
        chrom1 = c(1, 1, 1, 1, 1),
        chrom2 = c(1, 1, 2, 1, 3)
        )

我想将所有df[df$type=='BND',]个实例重新分配给INVTRA,具体取决于chrom1chrom2中的值。

我正在尝试使用forcats包中的fct_recode

library(forcats)

df$type <- ifelse(df$type=="BND", 
                  ifelse(df$chrom1 == df$chrom2,
                         fct_recode(df$type, BND="INV"),
                         fct_recode(df$type, BND="TRA")),
                  df$type)

然而,这将我的因素重新编号为数字:

  type chrom1 chrom2
1    1      1      1
2    3      1      1
3    1      1      2
4    2      1      1
5    4      1      3

这是我预期的结果:

  type chrom1 chrom2
1    INV      1      1 # BND -> INV as chrom1==chrom2
2    INV      1      1
3    TRA      1      2 # BND -> TRA as chrom1!=chrom2
4    DEL      1      1
5    TRA      1      3

如何以这种方式将因子分成两个级别?

4 个答案:

答案 0 :(得分:1)

我的思维方式如下:(1)索引要更改的行,(2)执行ifelse语句。我希望这会有所帮助:

  df <- data.frame(
  type = c("BND", "INV", "BND", "DEL", "TRA"),
  chrom1 = c(1, 1, 1, 1, 1),
  chrom2 = c(1, 1, 2, 1, 3)
)

indexBND<-which(df$type=="BND")
df$type[indexBND]<-ifelse(df$chrom1[indexBND] == df$chrom2[indexBND], df$type[indexBND] <- "INV", "TRA")

df
#   type chrom1 chrom2
# 1  INV      1      1
# 2  INV      1      1
# 3  TRA      1      2
# 4  DEL      1      1
# 5  TRA      1      3

干杯!

答案 1 :(得分:1)

您也可以使用case_when()

执行此操作
library(tidyverse)

df %>% 
  mutate(type = as.factor(case_when(
    type == 'BND' & chrom1 == chrom2 ~ 'INV', 
    type == 'BND' & chrom1 != chrom2 ~ 'TRA',
    TRUE  ~ as.character(type))))

数据:

df <- data.frame(
  type = c("BND", "INV", "BND", "DEL", "TRA"),
  chrom1 = c(1, 1, 1, 1, 1),
  chrom2 = c(1, 1, 2, 1, 3)
)

答案 2 :(得分:1)

为了完整起见,这里也是一个简洁的data.table解决方案:

library(data.table)
setDT(df)[type == "BND" & chrom1 == chrom2, type := "INV"][type == "BND", type := "TRA"][]
   type chrom1 chrom2
1:  INV      1      1
2:  INV      1      1
3:  TRA      1      2
4:  DEL      1      1
5:  TRA      1      3

好处是type通过引用更新,例如,不复制整个对象,仅适用于条件适用的那些行。

答案 3 :(得分:0)

或者只是

df$type[df$type == "BND"] <- with(df, 
                                  ifelse(df[type == "BND", ]$chrom1 == 
                                           df[type == "BND", ]$chrom2,
                                         "INV", "TRA"))
> df
  type chrom1 chrom2
1  INV      1      1
2  INV      1      1
3  TRA      1      2
4  DEL      1      1
5  TRA      1      3