Sample()比做一个数据帧。 R

问题描述 投票:1回答:2

我想通过使用sample()从数字1到20进行100次采样(并替换),然后将此数据转换为数据框并可视化。

df <- sample(1:20, 100, replace=TRUE)
df <- as.data.frame(df)
ggplot(df, aes(x= df, y= n)) + geom_bar(position = "fill")

试图找到一种更好的方法将sample()数据转换为数据帧。谢谢

r dataframe sample
2个回答
2
投票

不确定您的意思是更好的方法,但我想您可以做到

library(ggplot2)
df <- data.frame(x = sample(1:20, 100, replace=TRUE))
ggplot(df, aes(x)) + geom_bar()

或直接使用

ggplot(data.frame(x = sample(1:20, 100, replace=TRUE)), aes(x)) + geom_bar()

enter image description here


1
投票

一个更好的选择是利用tidyverse

library(dplyr)
library(ggplot2)
tibble(x = sample(1:20, 100, replace = TRUE)) %>%
      ggplot(aes(x)) + 
      geom_bar()

enter image description here


base R中,我们可以执行此操作而无需创建data.frame

barplot(sample(1:20, 100, replace = TRUE))
© www.soinside.com 2019 - 2024. All rights reserved.