Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R对Python:拆分R测试&;训练集,两行-类似于python drop_Python_R_Sample - Fatal编程技术网

R对Python:拆分R测试&;训练集,两行-类似于python drop

R对Python:拆分R测试&;训练集,两行-类似于python drop,python,r,sample,Python,R,Sample,我正在为初学者编写一个R与Python的博客,我正在做R部分。我想展示R中的最佳功能,但Python似乎更优雅地完成了这项特殊任务 我有一个数据框。我想把它分成一个测试和训练集。R用3行代码完成,python用2行代码完成。我想用两行类似于Python的代码来完成它,即 Python dfTrain = df.sample(frac=0.75) #Randomly sample 75% of the rows dfTest = df.drop(dfTrain.index) #Take the o

我正在为初学者编写一个R与Python的博客,我正在做R部分。我想展示R中的最佳功能,但Python似乎更优雅地完成了这项特殊任务

我有一个数据框。我想把它分成一个测试和训练集。R用3行代码完成,python用2行代码完成。我想用两行类似于Python的代码来完成它,即

Python

dfTrain = df.sample(frac=0.75) #Randomly sample 75% of the rows
dfTest = df.drop(dfTrain.index) #Take the other 25% of the rows
R

dfSample<-sample(1:nrow(df),size=0.75*nrow(df)) #this gives us 75% of the rows 
dfTrain<-df[dfSample,]              #select the rows in dfSample
dfTest<-df[-dfSample,]              #select the rows not in dfSample

dfSample我认为使用
dplyr时,R总是变得更优雅

我认为这是使用iris数据制作测试和训练集的一种非常好的方法

library(dplyr)

dfTrain <- sample_frac(iris, 0.75)
dfTest  <- setdiff(iris, dfTrain)
库(dplyr)

你能更详细地回答你的问题吗?你想用更少的行来做R版本吗?如果你想让它更短,就用代码问它。高尔菲我正在为初学者写一个R vs Python的博客,我正在做R部分。我想展示R中的最佳功能,但Python似乎能更优雅地完成这一特定任务。您可以尝试
dfTrain我同意Mhairi,但我更愿意在基本R中实现。这是迄今为止最好的答案。