简体   繁体   English

将占位符行添加到数据框列表

[英]Add placeholder rows to a list of dataframes

I have a list of dataframes. 我有一个数据框列表。

# Split dataframe into list of dataframes on two factor variables.
DF_list <- split(DF, list(DF$Unit_number, DF$Compartment), drop = TRUE)

I know how to remove rows from lists of dataframes. 我知道如何从数据帧列表中删除行。 But this time I want to add rows. 但是这次我要添加行。 1 placeholder row on the bottom of every dataframe in the list. 列表中每个数据框底部的1个占位符行。

This will prevent my rate of change calculations from creating false calculations for different factor levels that buttress each other in the normal dataframe structure. 这将防止我的变化率计算为正常数据框结构中相互支持的不同因子水平创建错误的计算。

Before splitting on compartment and unit number the dataframe looks like this; 在拆分隔离专区和单元编号之前,数据帧如下所示;

DF <- data.frame(Unit_number=c(1,1,2,2,2,1,2,2,1,1),
                 Compartment=c("Engine", "Engine", "Engine", "Transmission", "Transmission", "Transmission", "Tyres", "Tyres", "Tyres", "Tyres"))

The result needed is this; 需要的结果是这样;

Result <- data.frame(Unit_number=c(1,1,"Placeholder",2,"Placeholder",2,2,"Placeholder",1,"Placeholder",2,2,"Placeholder",1,1),
                 Compartment=c("Engine", "Engine","Placeholder", "Engine","Placeholder", "Transmission", "Transmission","Placeholder", "Transmission","Placeholder", "Tyres", "Tyres","Placeholder", "Tyres", "Tyres"))

If it's the same place holder that we want to add at the bottom of every list, we can create a Placeholder_df and rbind it at the end of every list. 如果与我们要在每个列表的底部添加的Placeholder_df ,则可以创建一个Placeholder_df并在每个列表的末尾添加rbind

Using purrr , map_dfr we could do 使用purrrmap_dfr我们可以做

Placeholder_df <-data.frame(Unit_number = "Placeholder",
                            Compartment = "Placeholder")

purrr::map_dfr(DF_list, ~ rbind(., Placeholder_df))

#   Unit_number  Compartment
#1            1       Engine
#2            1       Engine
#3  Placeholder  Placeholder
#4            2       Engine
#5  Placeholder  Placeholder
#6            1 Transmission
#7  Placeholder  Placeholder
#8            2 Transmission
#9            2 Transmission
#10 Placeholder  Placeholder
#11           1        Tyres
#12           1        Tyres
#13 Placeholder  Placeholder
#14           2        Tyres
#15           2        Tyres
#16 Placeholder  Placeholder

In base R, we could do 在基数R中,我们可以

do.call(rbind, lapply(DF_list, function(x) rbind(x, Placeholder_df)))

With base R , we can make use of Map 使用base R ,我们可以使用Map

do.call(rbind, Map(rbind, DF_list, list(Placeholder_df)))

data 数据

Placeholder_df <-data.frame(Unit_number = "Placeholder",
                        Compartment = "Placeholder")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM