在 R 中组合数据框的类别
Combining categories of a dataframe in R
我是 R 的新手并且
我在下面有以下数据框,y 轴上有 living_arrangements
顶点,x 轴上有 loneliness_level
顶点。
如果我想将 Alternate between parents and partner
和 College or student accomodation
合并到一个名为 other
的独特类别中,那么最好的方法是什么,这样我的数据框就会像下面这样?
loneliness_level
living_arrangements 1 2 3 4 5 6 7 8 9 10
Alone 1 1 0 2 0 1 1 3 1 4
Other 1 2 5 2 2 1 2 3 1 0
如果我们想得到总和,使用rowsum
out <- rowsum(m1, group = c(1, 2, 2))
row.names(out) <- c("Alone", "Other")
names(dimnames(out)) <- names(dimnames(m1))
-输出
> out
loneliness_level
living_arrangements 1 2 3 4 5 6 7 8 9 10
Alone 1 1 0 2 0 1 1 3 1 4
Other 1 2 5 2 2 1 2 3 1 0
数据
m1 <- structure(c(1, 0, 1, 1, 0, 2, 0, 1, 4, 2, 0, 2, 0, 0, 2, 1, 0,
1, 1, 0, 2, 3, 0, 3, 1, 0, 1, 4, 0, 0), .Dim = c(3L, 10L), .Dimnames = list(
living_arrangements = c("Alone", "Alternate between parents and partner",
"College or student accomodation"), loneliness_level = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10")))
我是 R 的新手并且
我在下面有以下数据框,y 轴上有 living_arrangements
顶点,x 轴上有 loneliness_level
顶点。
如果我想将 Alternate between parents and partner
和 College or student accomodation
合并到一个名为 other
的独特类别中,那么最好的方法是什么,这样我的数据框就会像下面这样?
loneliness_level
living_arrangements 1 2 3 4 5 6 7 8 9 10
Alone 1 1 0 2 0 1 1 3 1 4
Other 1 2 5 2 2 1 2 3 1 0
如果我们想得到总和,使用rowsum
out <- rowsum(m1, group = c(1, 2, 2))
row.names(out) <- c("Alone", "Other")
names(dimnames(out)) <- names(dimnames(m1))
-输出
> out
loneliness_level
living_arrangements 1 2 3 4 5 6 7 8 9 10
Alone 1 1 0 2 0 1 1 3 1 4
Other 1 2 5 2 2 1 2 3 1 0
数据
m1 <- structure(c(1, 0, 1, 1, 0, 2, 0, 1, 4, 2, 0, 2, 0, 0, 2, 1, 0,
1, 1, 0, 2, 3, 0, 3, 1, 0, 1, 4, 0, 0), .Dim = c(3L, 10L), .Dimnames = list(
living_arrangements = c("Alone", "Alternate between parents and partner",
"College or student accomodation"), loneliness_level = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10")))