如何使用带有R的变量镜像外部位置

如何使用带有R的变量镜像外部位置,r,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)) 我想“镜像此数据中的外部行,以获取此类数据并进行绘图” tes1 <- data.frame(x = c(0

我有一个数据框:

 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))

我想“镜像此数据中的外部行,以获取此类数据并进行绘图”

 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)

tes1这能满足你的需求吗

说明:我们首先将
tes
转换成一个带有
ftable(xtabs(…)
)的扁平表。然后我们只需复制第一列和最后一列,以及第一行和最后一行。然后我们给出新的列和行名称以反映额外的“侧翼”“行和列,最后使用
data.frame(表(…)

#转换为表格然后转换为矩阵
M
 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)
# 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)
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))