R将数据随机分为2部分 [英] R split data into 2 parts randomly

查看:419
本文介绍了R将数据随机分为2部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的数据帧随机分为两部分.例如,我想随机将70%的数据放入一个数据帧,将另外30%的数据随机放入另一个数据帧.有没有一种快速的方法来做到这一点?原始数据帧中的行数超过800000.我尝试了for循环,从行数中选择一个随机数,然后使用rbind()将该行绑定到第一个(70%)数据帧并将其从原始数据帧中删除,以获取另一个(30%)数据帧.但这非常慢.我可以用相对快速的方式做到这一点吗?

I am trying to split my data frame into 2 parts randomly. For example, I'd like to get a random 70% of the data into one data frame and the other 30% into other data frame. Is there a fast way to do this? The number of rows in the original data frame is over 800000. I've tried with a for loop, selecting a random number from the number of rows, and then binding that row to the first (70%) data frame using rbind() and deleting it from the original data frame to get the other (30%) data frame. But this is extremely slow. Is there a relatively fast way I could do this?

推荐答案

尝试

n <- 100
data <- data.frame(x=runif(n), y=rnorm(n))
ind <- sample(c(TRUE, FALSE), n, replace=TRUE, prob=c(0.7, 0.3))
data1 <- data[ind, ]
data2 <- data[!ind, ]

这篇关于R将数据随机分为2部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆