在R中获取一个data.frame的样本 [英] getting a sample of a data.frame in R
本文介绍了在R中获取一个data.frame的样本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在R中有以下数据框:
I have the following data frame in R:
id<-c(1,2,3,4,10,2,4,5,6,8,2,1,5,7,7)
date<-c(19970807,19970902,19971010,19970715,19991212,19961212,19980909,19990910,19980707,19991111,19970203,19990302,19970605,19990808,19990706)
spent<-c(1997,19,199,134,654,37,876,890,873,234,643,567,23,25,576)
df<-data.frame(id,date,spent)
我需要随机抽取3个客户(基于id),方式是客户的所有观察结果
I need to take a random sample of 3 customers (based on id) in a way that all observations of the customers be extracted.
推荐答案
您想在%和<$中使用% c $ c> unique
df[df$id %in% sample(unique(df$id),3),]
## id date spent
## 4 4 19970715 134
## 7 4 19980909 876
## 8 5 19990910 890
## 10 8 19991111 234
## 13 5 19970605 23
使用 data.table
以避免 $
引用
library(data.table)
DT <- data.table(df)
DT[id %in% sample(unique(id),3)]
## id date spent
## 1: 1 19970807 1997
## 2: 4 19970715 134
## 3: 4 19980909 876
## 4: 1 19990302 567
## 5: 7 19990808 25
## 6: 7 19990706 576
确保您始终评估data.table中的表达式。
This ensures that you are always evaluating the expressions within the data.table.
这篇关于在R中获取一个data.frame的样本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文