第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

從數(shù)據(jù)幀分層隨機(jī)抽樣

從數(shù)據(jù)幀分層隨機(jī)抽樣

叮當(dāng)貓咪 2019-08-19 15:33:18
從數(shù)據(jù)幀分層隨機(jī)抽樣我有一個(gè)格式的數(shù)據(jù)框:head(subset)# ants  0 1 1 0 1 # age   1 2 2 1 3# lc    1 1 0 1 0我需要根據(jù)年齡和lc創(chuàng)建帶有隨機(jī)樣本的新數(shù)據(jù)框。例如,我想要30個(gè)年齡的樣本:1和lc:1,30個(gè)樣本來(lái)自年齡:1和lc:0等。我確實(shí)看過(guò)隨機(jī)抽樣方法;newdata <- function(subset, age, 30)但這不是我想要的代碼。
查看完整描述

2 回答

?
牛魔王的故事

TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超3個(gè)贊

我建議使用stratified我的“splitstackshape”包或sample_n“dplyr”包:


## Sample data

set.seed(1)

n <- 1e4

d <- data.table(age = sample(1:5, n, T), 

                lc = rbinom(n, 1 , .5),

                ants = rbinom(n, 1, .7))

# table(d$age, d$lc)

對(duì)于stratified,您基本上指定數(shù)據(jù)集,分層列和表示每個(gè)組所需大小的整數(shù)或表示要返回的分?jǐn)?shù)的小數(shù)(例如,.1表示每組的10%)。


library(splitstackshape)

set.seed(1)

out <- stratified(d, c("age", "lc"), 30)

head(out)

#    age lc ants

# 1:   1  0    1

# 2:   1  0    0

# 3:   1  0    1

# 4:   1  0    1

# 5:   1  0    0

# 6:   1  0    1


table(out$age, out$lc)

#    

#      0  1

#   1 30 30

#   2 30 30

#   3 30 30

#   4 30 30

#   5 30 30

對(duì)于sample_n首先要?jiǎng)?chuàng)建一個(gè)分組表(使用group_by),然后指定想要觀測(cè)次數(shù)。如果你想要比例取樣,你應(yīng)該使用sample_frac。


library(dplyr)

set.seed(1)

out2 <- d %>%

  group_by(age, lc) %>%

  sample_n(30)


# table(out2$age, out2$lc)


查看完整回答
反對(duì) 回復(fù) 2019-08-19
?
函數(shù)式編程

TA貢獻(xiàn)1807條經(jīng)驗(yàn) 獲得超9個(gè)贊

我建議使用stratified我的“splitstackshape”包或sample_n“dplyr”包:


## Sample data

set.seed(1)

n <- 1e4

d <- data.table(age = sample(1:5, n, T), 

                lc = rbinom(n, 1 , .5),

                ants = rbinom(n, 1, .7))

# table(d$age, d$lc)

對(duì)于stratified,您基本上指定數(shù)據(jù)集,分層列和表示每個(gè)組所需大小的整數(shù)或表示要返回的分?jǐn)?shù)的小數(shù)(例如,.1表示每組的10%)。


library(splitstackshape)

set.seed(1)

out <- stratified(d, c("age", "lc"), 30)

head(out)

#    age lc ants

# 1:   1  0    1

# 2:   1  0    0

# 3:   1  0    1

# 4:   1  0    1

# 5:   1  0    0

# 6:   1  0    1


table(out$age, out$lc)

#    

#      0  1

#   1 30 30

#   2 30 30

#   3 30 30

#   4 30 30

#   5 30 30

對(duì)于sample_n首先要?jiǎng)?chuàng)建一個(gè)分組表(使用group_by),然后指定想要觀測(cè)次數(shù)。如果你想要比例取樣,你應(yīng)該使用sample_frac。


library(dplyr)

set.seed(1)

out2 <- d %>%

  group_by(age, lc) %>%

  sample_n(30)


# table(out2$age, out2$lc)


查看完整回答
反對(duì) 回復(fù) 2019-08-19
  • 2 回答
  • 0 關(guān)注
  • 643 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)