如何用R变量镜像外部位置

时间:2017-12-07 11:46:34

标签: r

我有一个数据框:

 tes <- data.frame(x = c(1, 1, 1, 2, 2, 2, 3, 3, 3), 
                      y = c(1, 2, 3, 1, 2, 3, 1, 2, 3), 
                      d = c(10, 20, 30, 100, 11, 12, 403, 43, 21))

他们在情节中看起来像这样

ggplot(aes(x = x, y = y), data = tes) + geom_point(aes(color = factor(d)), size = 5)

enter image description here

我希望&#34;镜像此数据中的外部行以获取此类数据并绘制

 tes1 <- data.frame(x = c(0, 0, 0, 0,0,  1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3,  3, 3, 3, 4, 4, 4, 4, 4), 
                       y = c(0, 1, 2, 3, 4, 0, 1, 2, 3, 4,   0, 1, 2, 3, 4, 0, 1, 2, 3, 4,  0, 1, 2, 3, 4), 
                       d = c(10, 10, 20, 30, 30, 10, 10, 20, 30, 30, 100, 100, 11, 12, 12, 403, 403, 43, 21, 21, 403, 403, 43, 21, 21))
ggplot(aes(x = x, y = y), data = tes1) + geom_point(aes(color = factor(d)), size = 4)

enter image description here

1 个答案:

答案 0 :(得分:1)

这是否符合您的要求?

说明:我们首先将tes转换为带有ftable(xtabs(...)的展平表格。然后我们简单地复制第一列和最后一列,以及第一行和最后一行。然后我们给出新的列和行名称以反映额外的&#34;侧翼&#34;行和列,最后使用dataframe

转换回长data.frame(table(...))
# Convert to table then matrix
m <- ftable(xtabs(d ~ x + y, data = tes));
class(m) <- "matrix";

# Replicate first and last column/row by binding to the beginning
# and end, respectively of the matrix
m <- cbind(m[, 1], m, m[, ncol(m)]);
m <- rbind(m[1, ], m, m[nrow(m), ]);

# Set column/row names
rownames(m) <- seq(min(tes$x) - 1, max(tes$x) + 1);
colnames(m) <- seq(min(tes$y) - 1, max(tes$y) + 1);

# Convert back to long dataframe
tes.ext <- data.frame(as.table(m));
colnames(tes.ext) <- colnames(tes);

# Plot
ggplot(aes(x = x, y = y), data = tes.ext) + geom_point(aes(color = factor(d)), size = 5)

enter image description here

数据

tes <- data.frame(x = c(1, 1, 1, 2, 2, 2, 3, 3, 3), 
                  y = c(1, 2, 3, 1, 2, 3, 1, 2, 3), 
                  d = c(10, 20, 30, 100, 11, 12, 403, 43, 21))