计算小于 R 中变量的值的因子数
Counting the numbers of factors for values smaller than a variable in R
我有以下 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
到目前为止我还没有找到任何直接的东西,所以我将非常感谢你的帮助。
尝试
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)
我有以下 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
到目前为止我还没有找到任何直接的东西,所以我将非常感谢你的帮助。
尝试
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)