我有一个约200列的数据框,想要生成一个2x2列联表。 我的代码如下:
d <- structure(list(Time=structure(17942:17947, class="Date"),
x1=c(NA, NA, 17L, 29L, 27L, 10L), x2=c(30L, 19L, 22L, 20L, 11L,
24L), x3=c(NA, 23L, 22L, 27L, 21L, 26L), x4=c(30L, 28L, 23L,
24L, 10L, 17L), x5=c(12L, 18L, 17L, 16L, 30L, 26L)),
row.names=c(NA, 6L), class="data.frame")
x <- t(apply(d[,-1], 1, function(x) x > median(x, na.rm=TRUE)))
nr <- nrow(x)
dx <- diff(x)
lw <- (dx == 1)*1
wl <- (dx == -1)*2
dd <- (dx == 0)
ww <- (dd & x[-nr,] == 1)*3
ll <- (dd & x[-nr,] == 0)*4
tab <- c("lose/win", "win/lose", "win/win", "lose/lose")[lw + wl + ww + ll]
d0 <- d
d0[-1,-1] <- tab
d0
这是输出:
# Time x1 x2 x3 x4 x5
# 1 2019-02-15 <NA> 30 <NA> 30 12
# 2 2019-02-16 <NA> lose/lose <NA> lose/win lose/lose
# 3 2019-02-17 <NA> lose/lose win/lose win/win lose/lose
# 4 2019-02-18 lose/win lose/lose lose/win win/lose lose/lose
# 5 2019-02-19 win/win lose/lose win/lose lose/lose lose/win
# 6 2019-02-20 win/lose lose/lose lose/win lose/lose win/win
我正在寻找一种有效的方法来计算每一行的所有四种可能组合,而忽略NA。
谢谢!
答案 0 :(得分:0)
像这样吗?
tbl <- reshape2::melt(d0[-1, ], id.vars = "Time")[3]
tbl <- do.call(rbind, strsplit(as.character(tbl$value), "/"))
tbl <- as.data.frame(tbl)
列联表。
xtabs(~ ., tbl)
# V2
#V1 lose win
# lose 10 5
# win 4 3
替代方式。
table(tbl)
# V2
#V1 lose win
# lose 10 5
# win 4 3