Arun Vaibhav
Arun Vaibhav

Reputation: 11

How to select random samples in a dataframe?

I am using the following command to create 50 random samples in a dataset. and I want to know the mean of observations(area).

ds1 %>%
  sample_n(size = 50) %>%
  summarise(x_bar = mean(area))

But I get

Error in function_list[[i]](value) : could not find function "sample_n"

I tried searching for the function sample_n using getAnywhere() but I didn't find the object.

Instead it works when I use,

ds1_samp3 <- 
  ames[sample(nrow(ds1), 1000), ]

ds1_samp3 %>% 
  summarise(mu = mean(area))

Just want to know why the first command doesn't work?

Thanks, Vkva

Upvotes: 0

Views: 1510

Answers (2)

user3349904
user3349904

Reputation: 34

sample_n is contained in the dplyr package. It will work as long as you have installed & imported said package in your session. Substituting with sample (from base) will not work because it does not assume data.frame input, whereas sample_n does.

Upvotes: 1

Thom Quinn
Thom Quinn

Reputation: 308

sample_n is not a function in R. Use sample instead:

ds1 %>%
  sample(size = 50) %>%
  summarise(x_bar = mean(area))

Upvotes: 0

Related Questions