gpt4 book ai didi

r - 如何按个人采样/划分面板数据(最好使用插入符号库)?

转载 作者:行者123 更新时间:2023-12-03 14:29:09 25 4
gpt4 key购买 nike

我想对面板数据进行分区并保留数据的面板性质:

      library(caret)
library(mlbench)

#example panel data where id is the persons identifier over years
data <- read.table("http://people.stern.nyu.edu/wgreene/Econometrics/healthcare.csv",
header=TRUE, sep=",", na.strings="NA", dec=".", strip.white=TRUE)

## Here for instance the dependent variable is working
inTrain <- createDataPartition(y = data$WORKING, p = .75,list = FALSE)

# subset into training
training <- data[ inTrain,]
# subset into testing
testing <- data[-inTrain,]
# Here we see some intersections of identifiers
str(training$id[10:20])
str(testing$id)

但是我想,在对数据进行分区或采样时,避免将同一个人(id)分成两个数据集。他们是一种从数据中随机采样/分区并将个体分配给相应分区而不是观察的方法?

我试图采样:
    mysample <- data[sample(unique(data$id), 1000,replace=FALSE),] 

然而,这破坏了数据的面板性质......

最佳答案

我认为使用 sample() 的采样方法存在一个小错误。 : 它正在使用 id像行号一样的变量。相反,该函数需要获取属于一个 ID 的所有行:

nID <- length(unique(data$id))
p = 0.75
set.seed(123)
inTrainID <- sample(unique(data$id), round(nID * p), replace=FALSE)
training <- data[data$id %in% inTrainID, ]
testing <- data[!data$id %in% inTrainID, ]

head(training[, 1:5], 10)
# id FEMALE YEAR AGE HANDDUM
# 1 1 0 1984 54 0.0000000
# 2 1 0 1985 55 0.0000000
# 3 1 0 1986 56 0.0000000
# 8 3 1 1984 58 0.1687193
# 9 3 1 1986 60 1.0000000
# 10 3 1 1987 61 0.0000000
# 11 3 1 1988 62 1.0000000
# 12 4 1 1985 29 0.0000000
# 13 5 0 1987 27 1.0000000
# 14 5 0 1988 28 0.0000000


dim(data)
# [1] 27326 41
dim(training)
# [1] 20566 41
dim(testing)
# [1] 6760 41
20566/27326
### 75.26% were selected for training

让我们检查类(class)余额,因为 createDataPartition将在所有集合中保持 WORKING 的类平衡。
table(data$WORKING) / nrow(data)
# 0 1
# 0.3229525 0.6770475
#
table(training$WORKING) / nrow(training)
# 0 1
# 0.3226685 0.6773315
#
table(testing$WORKING) / nrow(testing)
# 0 1
# 0.3238166 0.6761834
### virtually equal

关于r - 如何按个人采样/划分面板数据(最好使用插入符号库)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31007461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com