-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgeneral_helpers.R
executable file
·46 lines (40 loc) · 1.51 KB
/
general_helpers.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# =============================================================================================== #
# General helper functions #
# =============================================================================================== #
# "Not in" operator, contrary of %in%
"%nin%" <- Negate("%in%")
# Rearrange columns
rearrange_cols <- function(df, col_order = colnames(df), new_colnames = NULL){
df <- df[col_order]
if(!is.null(new_colnames)){ colnames(df) <- new_colnames }
return(df)
}
# Filter list of vectors
filter_vector_list <- function(vec_list, filt_val){
vec_filt_list <- list()
for(i in 1:length(vec_list)){
name <- names(vec_list[i])
vec_filt_list[[name]] <- vec_list[[i]] %>% magrittr::extract(. %in% filt_val)
}
return(vec_filt_list)
}
# bind cols with different length
bind_cols2 <- function(list, name = names(list)){
N <- list %>% purrr::map(~nrow(.x)) %>% unlist() %>% max()
for(i in 1:length(list)){
numrow <- nrow(list[[i]])
numcol <- ncol(list[[i]])
n = N-numrow
if(numrow == N){ list[[i]] > list[[i]] }
else{ list[[i]][(numrow+1):(numrow+n),] <- NA }
}
list_bind <- bind_cols(list) %>% magrittr::set_colnames(name)
return(list_bind)
}
# add na rows to empty dfs
add_na_rows <- function(df, numcols=ncol(df), namecols = colnames(df)){
if( nrow(df) == 0 ) {
df <- df %>% dplyr::bind_rows(data.frame(matrix(rep(NA, numcols), nrow = 1)) %>% magrittr::set_colnames(namecols))
}
return(df)
}