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

时间:2019-03-19 04:34:56

标签: r list lapply

我有一个数据帧列表。

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

我知道如何从数据框列表中删除行。但是这次我要添加行。 列表中每个数据框底部的1个占位符行。

这将防止我的变化率计算为正常数据帧结构中相互支持的不同因子水平创建错误的计算。

在分割隔离专区和单位编号之前,数据帧如下所示;

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"))

需要的结果是这样

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"))

2 个答案:

答案 0 :(得分:1)

如果我们要在每个列表的底部添加相同的占位符,则可以在每个列表的末尾创建一个Placeholder_dfrbind

我们可以使用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

在基数R中,我们可以做到

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

答案 1 :(得分:1)

有了base R,我们就可以利用Map

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

数据

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