将前25%的行分配为T,将其他行分配为F的列表数据帧(assign first 25 percent of rows as T and others as F from dataframes of list)
我有一个列表中随机采样的数据帧行列表。 我想将所有数据帧中前25%的行分配为T,将其他行分配为F.例如:
vec.1 <- c(1:574) vec.2 <- c(3001:3574) df.1 <- data.frame(vec.1, vec.2) df.2 <- data.frame(vec.2, vec.1) my_list <- replicate(10, df.1[sample(nrow(df.1)),] , simplify = FALSE)在这个数据帧列表中,我想将前25%的行分配为F,将所有其他行分配为T.如何执行此操作?
I have a list of randomly sampled rows of dataframes in list. I would like to assign the first 25 percent of rows in all dataframe as T and other rows as F. For example:
vec.1 <- c(1:574) vec.2 <- c(3001:3574) df.1 <- data.frame(vec.1, vec.2) df.2 <- data.frame(vec.2, vec.1) my_list <- replicate(10, df.1[sample(nrow(df.1)),] , simplify = FALSE)In this list of dataframes I would like to assign the first 25 percent of rows as F and all other rows as T. How to do this?
最满意答案
您可以轻松编写如下函数以在lapply :
myFun <- function(indf) { indf$vec.3 <- seq_len(nrow(indf)) <= .25*nrow(indf) indf }然后用法就是lapply(my_list, myFun) 。
You can easily write a function like the following to be used within lapply:
myFun <- function(indf) { indf$vec.3 <- seq_len(nrow(indf)) <= .25*nrow(indf) indf }Usage would then just be lapply(my_list, myFun).
更多推荐
发布评论