R对Python:拆分R测试&;训练集,两行-类似于python drop
我正在为初学者编写一个R与Python的博客,我正在做R部分。我想展示R中的最佳功能,但Python似乎更优雅地完成了这项特殊任务 我有一个数据框。我想把它分成一个测试和训练集。R用3行代码完成,python用2行代码完成。我想用两行类似于Python的代码来完成它,即 PythonR对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
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中实现。这是迄今为止最好的答案。