【问题标题】:R: Converting "tables" to "data frame: 'height' must be a vector or a matrixR:将“表格”转换为“数据框:'高度'必须是向量或矩阵
【发布时间】:2023-04-06 14:19:01
【问题描述】:

我在 R 中找到了以下代码,它绘制了一个直方图并将一些条形涂成红色:

n = floor(rnorm(10000, 500, 100))
t = table(n)

# get color counts
r <- floor(length(t)/2)
b <- length(t) - r

# repeat red r times, repeat black b times
barplot(t, col = rep(c("red", "black"), c(r, b)), border = NA)

# use "topleft" to place legend
legend("topleft", legend=c("group a", "group b"),
       col=c("red", "black"), lty = 1, cex=0.8)
title(main = "some title", 
      sub = "some title")

如上代码所示,这要求数据为“表格”格式。

问题:我正在尝试制作相同的图表,但改用“数据框”。由于我更熟悉数据框,这将使我更加灵活(例如,将颜色随机分配给直方图中的条形)。我尝试编写以下代码:

#randomly assign colors to different bars in the histogram and convert table into data frame

color <- c("red", "black")     
color_1 <- as.factor(sample(color, 10000, replace=TRUE, prob=c(0.5, 0.5)))
t = data.frame(t)
t$color_1 <-color_1
barplot(t, color = t$color_1)

但这会返回几个错误:

Error in `$<-.data.frame`(`*tmp*`, color_1, value = c(1L, 1L, 1L, 2L,  : 
  replacement has 10000 rows, data has 574

由于某种原因,数据有 583 行,而不是最初在(所有行都去哪儿了!?n = floor(rnorm(10000, 500, 100)) 命令中指定的 10,000 行。

忽略这一点,如果我假设 583 行:

color <- c("red", "black")     
color_1 <- as.factor(sample(color, 574, replace=TRUE, prob=c(0.5, 0.5)))
t = data.frame(t)
t$color_1 <-color_1
barplot(t, color = t$color_1)

我收到一个新错误:

Error in barplot.default(t, color = t$color_1) : 
  'height' must be a vector or a matrix

谁能告诉我如何解决这个错误?

谢谢

【问题讨论】:

    标签: r plot graph data-visualization data-manipulation


    【解决方案1】:

    data.frame使用公式法

    t <- as.data.frame(t)
    color <- c("red", "black")     
    color_1 <- sample(color, nrow(t), replace=TRUE, prob=c(0.5, 0.5))
    barplot(Freq ~ n, data = t, col = color_1, border = NA)
    

    -输出

    【讨论】:

    • 感谢您的回答!对我来说最大的谜团之一:
    • n = floor(rnorm(1000, 500, 100)) t = table(n) t
    • 为什么 "t" 没有 1000 行?
    • @Noob 因为table 的长度只有 585 左右。它创建了一个频率的命名向量,因此只有一个唯一的名称及其频率t = table(n); length(t) [1] 585
    • @Noob 如果你想有 1000 行,那么一些观察结果将被复制,即tibble(n1 = n) %&gt;% add_count(n1)
    猜你喜欢
    • 2018-05-15
    • 1970-01-01
    • 2014-06-15
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多