如何将有序数据帧拆分为上半部分和下半部分 [英] How to split an ordered dataframe into first half and second half
问题描述
我想将数据帧传递给将其分为两半但保留顺序的函数(例如,一个返回的df中包含10行df和1-5行,而另一个返回的df中包含6-10行) 。我正在尝试使用函数 split()
来(返回2个df的列表,但是当我使用 sample()
混合订单。
I want to pass a data frame to a function which splits it into two halves but retains the order (e.g. 10 row df and rows 1-5 are in one returned df and rows 6-10 are in the other returned df). I'm trying to use the function split()
to( return a list of the 2 dfs but when I use sample()
it mixes up the orders.
split_df<- function(df)
{
test = split(df, sample(1:2,length(df)/2))
return(test)
}
我在输入 sample()
时遇到麻烦。我知道有人问过要在此处拆分数据帧的问题,但我可以出于某种原因而无法使用。除了 sample()
之外,我还能使用什么?
I'm having trouble with the inputs for sample()
. I know people have asked about splitting data frames here but I can't get this to work for some reason. What else can I use besides sample()
?
推荐答案
sample
函数的名称可能会让您失望,它打算用于随机采样,请尝试 rep()
代替:
The name of the sample
function may be throwing you off. It's intended for random sampling. Try rep()
instead:
split_df <- function(df) {
test <- split(df, rep(1:2,each=length(df)/2))
return(test)
}
这篇关于如何将有序数据帧拆分为上半部分和下半部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!