如何编写一个函数以基于变量的值创建多个数据框?

时间:2019-06-25 20:02:01

标签: r

我有一个数据框,其中包含一个名为ProgramName的变量,该变量包含不同程序的名称,但有时此名称会更改。我想创建一个为每个程序名称创建一个数据框的函数。与子功能相似。

数据框中还有其他特征也需要过滤,因此以下代码可以解决此问题

ma <- as.data.frame(Missing_AttendanceKIDS, stringsAsFactors = FALSE)
mi <- as.data.frame(Missing_AttendanceSIS, stringsAsFactors = FALSE)
mi <- mi %>% select(c("ProgramName", "FnLnDOB", "Funding", "Missing     Days"))
ma$ProgramName <- as.character(ma$ProgramName)
ma <- ma[!(ma$Funder == "School Board (FL)" & ma$Issue == "non-existent"), ]
HaveFirstTermCode <- ma %>% subset(FirstTermCodeDate != "NULL")
ma <- ma[!(ma$FirstTermCodeDate != "NULL"), ]
InvalidTermCode <- ma %>% subset(Issue == "invalid term code")
ma <- ma[!(ma$Issue == "invalid term code"), ]
Blkgenerator <- ma %>% subset(ma$Issue == "non-existent" & ma$Funder != "School Board (FL)")
ma <- ma[!(ma$Issue == "non-existent" & ma$Funder != "School Board (FL)"), ]

ma$ProgramName <- as.factor(ma$ProgramName)

下面的代码是我想要的功能。如果可能的话,还要给结果数据框指定程序的名称。

Missing_Attendance_Acadiana <- subset(ma, ma$ProgramName == "Acadiana" & ma$Issue == "blank")
Missing_Attendance_Alabama <- subset(ma, ma$ProgramName == "Alabama Family Services" & ma$Issue == "blank")
Missing_Attendance_Beaufort <- ma[ma$ProgramName %like% "Beaufort" & ma$Issue == "blank", ]
Missing_Attendance_Piedmont <- ma[ma$ProgramName %like% "Piedmont" & ma$Issue == "blank", ]

获取数据框后,我将运行以下函数以使用R Markdown创建一个带有数据框的html。

tablemu = function(df) kable(df, row.names = FALSE, caption = "Missing Attendance") %>%
kable_styling(bootstrap_options = "striped", position = "center", full_width = T, fixed_thead = list(enabled = T, background = "Orange"), stripe_color =    list(enabled = T, background = "yellow") ) %>%
column_spec(1:4, bold = T, border_left = T, border_right = T)

1 个答案:

答案 0 :(得分:0)

只需使用split即可根据因子创建数据帧的命名列表,然后使用lapply通过所需的方法运行它。

sub <- ma[ma$Issue == "blank",]
df_list <- split(sub, sub$ProgramName)

lapply(df_list, tablemu)

或者,使用bytapply的面向对象包装器)简化上述两个调用。下面将输出您的HTML输出的打印列表:

sub <- ma[ma$Issue == "blank",]
by(sub, sub$ProgramName, tablemu)

无需在全局环境中注入很多变量。