随机子集数据后如何在R中写入剩余的数据帧 [英] How to write the remaining data frame in R after randomly subseting the data
问题描述
我从数据框中随机抽取了一个样本.但是我不知道如何获取剩余的数据框.
I took a random sample from a data frame. But I don't know how to get the remaining data frame.
df <- data.frame(x=rep(1:3,each=2),y=6:1,z=letters[1:6])
#select 3 random rows
df[sample(nrow(df),3)]
我想要的是将剩余的数据框与其他 3 行一起获取.
What I want is to get the remaining data frame with the other 3 rows.
推荐答案
sample
每次运行时都会设置一个随机种子,因此如果你想重现它的结果,你要么需要 set.seed
或将其结果保存在变量中.
sample
sets a random seed each time you run it, thus if you want to reproduce its results you will either need to set.seed
or save its results in a variable.
解决您的问题,您只需在索引前添加 -
即可获得数据集的其余部分.另外,如果您想选择行(与您的问题不同),请不要忘记在 indx
后面添加一个逗号
Addressing your question, you simply need to add -
before your index in order to get the rest of the data set.
Also, don't forget to add a comma after the indx
if you want to select rows (unlike in your question)
set.seed(1)
indx <- sample(nrow(df), 3)
你的子集
df[indx, ]
# x y z
# 2 1 5 b
# 6 3 1 f
# 3 2 4 c
剩余数据集
df[-indx, ]
# x y z
# 1 1 6 a
# 4 2 3 d
# 5 3 2 e
这篇关于随机子集数据后如何在R中写入剩余的数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!