如何编写以相同方式操作多个数据框的函数?

时间:2018-10-30 21:00:45

标签: r function

完整的新手。我不知道如何编写函数。我有几个数据框,所有这些数据框都需要以相同的方式进行操作,并且输出应该是具有相同名称的数据框。我有可以操纵单个数据框的功能代码。我希望能够一次操纵多个。

以下是df的两个示例:

ex1 <- structure(list(info1 = c("Day", "2018.04.03  10:47:33", "2018.04.03  11:20:04", "2018.04.03  11:35:04"), info2 = c("Status_0", "Ok", "Ok", "Ok"
), X = c(200L, 1L, 2L, 3L), X.1 = c(202.5, 1, 2, 3), X.2 = c(205L, 
1L, 2L, 3L), X.3 = c(207.5, 1, 2, 3), X.4 = c(210L, 1L, 2L, 3L
), X.5 = c(212.5, 1, 2, 3), X.6 = c(215L, 1L, 2L, 3L)), class = "data.frame", row.names = c(NA, -4L))

ex2 <- structure(list(info1 = c("Day", "2018.04.10  12:47:33", "2018.04.10  13:20:04", "2018.04.10  13:35:04"), info2 = c("Status_0", "Ok", "Ok", "Ok"
), X = c(200L, 1L, 2L, 3L), X.1 = c(202.5, 1, 2, 3), X.2 = c(205L, 
1L, 2L, 3L), X.3 = c(207.5, 1, 2, 3), X.4 = c(210L, 1L, 2L, 3L
), X.5 = c(212.5, 1, 2, 3), X.6 = c(215L, 1L, 2L, 3L)), class = "data.frame", row.names = c(NA, -4L))

以下是用于操作“ ex1”的功能代码

library(tidyverse)
library(lubridate)

  colnames(ex1) <- ex1[1,]                            
  ex1 <- ex1 %>% 
    slice(-1) %>%                                                               
    rename(Date.Time = "Date/Time") %>% 
    mutate(timestamp = parse_date_time(Date.Time, "%Y.%m.%d %H:%M:%S")) %>%     
    select(timestamp, Date.Time, everything()) %>% select(-Date.Time) %>%       
    select(-c(Status_0:"202.5", "212.5":"215"))
  colnames(ex1)[-1] <- paste("raw", colnames(ex1)[-1], sep = "_")

第二个问题:假设我想更改函数,使其接受df,但也接受类型(即raw或comp),并且函数输入将为tidydatafunc(df,type)。如果我输入type = comp,它将把我具有“ raw”的代码的最后一行更改为“ comp”。我该如何更改功能以适应这种情况?

任何帮助将不胜感激。我相信这对你们大多数人来说都是基本的东西!

1 个答案:

答案 0 :(得分:2)

将脚本包装在函数中并指定参数。

my_fun <- function(df, type = 'comp') {
  # basic input validation is extremely useful
  stopifnot(is.data.frame(df))
  stopifnot(is.character(type))

  colnames(df) <- df[1,]                            
  ex1 <- df %>% 
  slice(-1) %>%                                                               
  rename(Date.Time = "Date/Time") %>% 
  mutate(timestamp = parse_date_time(Date.Time, "%Y.%m.%d %H:%M:%S")) %>%     
  select(timestamp, Date.Time, everything()) %>% select(-Date.Time) %>%       
  select(-c(Status_0:"202.5", "212.5":"215"))
  # pass the character type
  colnames(df)[-1] <- paste(type, colnames(df)[-1], sep = "_")
  return(df)
}

然后就可以使用它了。

my_fun(ex1, "comp") # view
new_ex1 <- my_fun(ex1, "comp") # save to variable new_ex1