JJ lee
JJ lee

Reputation: 11

Sample() than make a dataframe. R

I want to Sample 100 times (with replacement) from the numbers 1 to 20 by using sample() then turn this data into a data frame and visualize it.

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

trying to find a better way to turn sample() data into a data frame. Thanks

Upvotes: 1

Views: 50

Answers (2)

akrun
akrun

Reputation: 887851

A better option would be to make use of tidyverse

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

enter image description here


In base R, we can do this without creating a data.frame

barplot(sample(1:20, 100, replace = TRUE))

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389235

Not sure what you mean by better way, but I guess you could do

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

Or use it directly

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

enter image description here

Upvotes: 2

Related Questions