[英]Conditionally split factor level into two different levels
我有一個數據框,例如:
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',]
實例重新分配給INV
或TRA
具體取決於chrom1
和chrom2
的值。
我試圖用fct_recode
從forcats包像這樣:
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
如何以這種方式將因子分成兩個級別?
我的思考方式如下:(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
干杯!
你也可以用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)
)
為了完整起見,這里也是一個簡潔的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
通過引用更新,例如,不復制整個對象,並且僅適用於條件適用的那些行。
要不就
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.