[英]Looping over factor levels in R - how to operate two consecutive levels
我需要在 R data.frame 中循環因子級別。 在循環內部,我需要對包含由這些級別對定義的子集的 data.frames 進行操作。 這些對是該因素的兩個連續的唯一級別。
這是我嘗試過的示例:
require(dplyr)
df <- data.frame(fac = rep(c("A", "B", "C"), 3))
for(i in levels(fac)){
if(i != levels(fac)[length(levels(fac))]){
df %>% filter(fac %in% c(i, i + 1))
}
}
我嘗試包含級別i
及其后續級別,但顯然表達式i + 1
不會成功。 如何解決這個問題? 我是否必須使可變fac
數值化,或者是否有更簡潔的解決方案?
編輯:輸出(對於這個例子)應該是這兩個 data.frames:
dfAB <- df %>% filter(fac %in% c("A", "B"))
dfBC <- df %>% filter(fac %in% c("B", "C"))
問題是,您遍歷 fac 的所有級別,這是一個字符向量,因此R
不能將 1 添加到i
。
以下工作:
library(dplyr)
df <- data.frame(fac = rep(c("A", "B", "C"), 3))
df <- df %>%
mutate(fac = factor(fac, levels = c("A", "B", "C")))
for(i in seq_along(levels(df$fac))){
if(i != length(levels(df$fac))){
df %>% filter(fac %in% c(levels(fac)[i], levels(fac)[i+1])) %>% print()
}
}
# fac
# 1 A
# 2 B
# 3 A
# 4 B
# 5 A
# 6 B
# fac
# 1 B
# 2 C
# 3 B
# 4 C
# 5 B
# 6 C
fac
列必須是一個factor
(否則過濾不起作用)。 我在循環中添加了print()
以打印結果,但您可能希望將其存儲在某處(例如在列表中)。
一個沒有循環的解決方案。
library(dplyr)
# Create example data frame
df <- data.frame(fac = rep(c("A", "B", "C"), 3),
stringsAsFactors = TRUE)
# Create all the combinations of factor
m <- combn(unique(df$fac), m = 2)
# Check the difference between factor level, only keep those differ by 1
# Create a data frame with the right combination
re <- which(as.numeric(m[2, ]) - as.numeric(m[1, ]) != 1)
m2 <- as.data.frame.matrix(m[, -re])
# Filter df by m2
df_final <- lapply(m2, function(col){
df %>% filter(fac %in% col)
})
df_final
# $V1
# fac
# 1 A
# 2 B
# 3 A
# 4 B
# 5 A
# 6 B
#
# $V2
# fac
# 1 B
# 2 C
# 3 B
# 4 C
# 5 B
# 6 C
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.