我有以下R数据,我希望通过计算每个因子看到的值小于x的值来处理。
structure(list(variable = structure(c(2L, 2L, 1L, 1L, 2L, 3L,
2L, 2L, 1L, 2L, 3L, 3L, 1L, 3L, 2L, 1L, 2L), .Label = c("A",
"B", "C"), class = "factor"), x = c(0, 0.01, 0.03, 0.05, 0.33,
0.38, 0.02, 0.03, 0.1, 0.15, 0.41, 0.42, 0.38, 0.07, 0.32, 0.05,
0.04)), .Names = c("variable", "x"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17"))
我最终得到的数据框如下:
x A B C
0 00 0 1 0
0.01 0 2 0
0.02 0 3 0
0.03 1 4 0
0.04 1 5 0
0.05 3 5 0
0.07 3 5 1
and so on
到目前为止我还没有发现任何事情,所以我非常感谢您的帮助。
答案 0 :(得分:2)
尝试
tbl1 <- table(df1[2:1])
res <- apply(tbl1, 2, cumsum)
head(res, 7)
# variable
# A B C
# 0 0 1 0
# 0.01 0 2 0
# 0.02 0 3 0
# 0.03 1 4 0
# 0.04 1 5 0
# 0.05 3 5 0
# 0.07 3 5 1
或者是一行代码(来自@David Arenburg的评论)
apply(table(df1), 1, cumsum)