我有以下类型的表:
| 经济特区 | 班级 | 瓦尔 |
|---|---|---|
| 1_1_1 | 1 | 2 |
| 1_1_1 | 5 | 2 |
| 1_1_2 | 5 | 2 |
| 1_1_3 | 1 | 1 |
| 1_1_3 | 5 | 2 |
| 1_1_4 | 1 | 1 |
| 1_1_5 | 2 | 1 |
| 1_2_1 | 1 | 2 |
| 1_2_1 | 5 | 2 |
为了将“Class”列分散到多个新列中,从“Val”列中获取价值,我使用了pivot_wider,一切顺利。我输入了这段代码:
pivot_wider(names_from = Class, values_from = Val, names_sort=T, values_fill = list(n = 0))
得到这样的结果:
| 塞兹 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| 1_1_1 | 2 | 0 | 0 | 0 | 2 | 0 | 0 |
| 1_1_2 | 0 | 0 | 0 | 0 | 2 | 0 | 0 |
| 1_1_3 | 1 | 0 | 0 | 0 | 2 | 0 | 0 |
不幸的是,我必须使用外部计算机,其中仅存在基本的 R 包,并且请求附加包的时间并不短。
我尝试使用这个解决方案:
newdata <- xtabs(dat$Val ~ dat$Sez + dat$Class)
但它给了我每行的频率分布:
| 经济特区 | 班级 | 频率 |
|---|---|---|
| 1_1_1 | 1 | 2 |
| 1_1_2 | 1 | 0 |
| 1_1_3 | 1 | 1 |
| 1_1_4 | 1 | 1 |
| 1_1_5 | 1 | 0 |
| 1_2_1 | 1 | 1 |
我正在寻找一种具有 R 基本功能的解决方案,该解决方案为我提供了一个与使用pivot_wider 所使用的对象相同的对象。
我们创建“类”factor并使用xtabs
df1$Class <- factor(df1$Class, levels = 1:7)
xtabs(Val ~ SEZ + Class, df1)
Run Code Online (Sandbox Code Playgroud)
-输出
Class
SEZ 1 2 3 4 5 6 7
1_1_1 2 0 0 0 2 0 0
1_1_2 0 0 0 0 2 0 0
1_1_3 1 0 0 0 2 0 0
1_1_4 1 0 0 0 0 0 0
1_1_5 0 1 0 0 0 0 0
1_2_1 2 0 0 0 2 0 0
Run Code Online (Sandbox Code Playgroud)
如果我们需要一个data.frame输出
out <- as.data.frame.matrix( xtabs(Val ~ SEZ + Class, df1))
out$SEZ <- row.names(out)
row.names(out) <- NULL
Run Code Online (Sandbox Code Playgroud)
df1 <- structure(list(SEZ = c("1_1_1", "1_1_1", "1_1_2", "1_1_3", "1_1_3",
"1_1_4", "1_1_5", "1_2_1", "1_2_1"), Class = c(1L, 5L, 5L, 1L,
5L, 1L, 2L, 1L, 5L), Val = c(2L, 2L, 2L, 1L, 2L, 1L, 1L, 2L,
2L)), row.names = c(NA, -9L), class = "data.frame")
Run Code Online (Sandbox Code Playgroud)