Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consider adding tags2list and list2tags functions #76

Open
trinker opened this issue Aug 14, 2020 · 1 comment
Open

Consider adding tags2list and list2tags functions #76

trinker opened this issue Aug 14, 2020 · 1 comment

Comments

@trinker
Copy link
Owner

trinker commented Aug 14, 2020

## convert names columns with one hot encoding to list of column names
tags2list <- function(data, ...){

    data %>%
        select(...) %>%
        {Map(function(x, y){
            ifelse(x > 0, y, NA)
        }, ., names(.))} %>%
        unlist(use.names = FALSE)

}


list2tags <- function(data, ncol = length(unique(na.omit(unlist(data))))){
# browser()
    lapply(data, function(x){
            x %>%
                matrix(ncol = ncol) %>%
                as.data.frame()
        }) %>%
        bind_rows() %>%
        {Map(function(x){

            setNames(tibble(x = ifelse(is.na(x), 0L, 1L)), unique(na.omit(x)) )

        }, .)} %>%
        bind_cols()

}
@trinker
Copy link
Owner Author

trinker commented Aug 25, 2020

## convert names columns with one hot encoding to list of column names
tags2list <- function(data, ...){

    `%>%` <- dplyr::`%>%`

    if (length(list(...)) > 0  && !is.null(...)) {

        m <- data %>%
            dplyr::select(...) 

    } else {

        m <- data 

    }

    m %>%
        {Map(function(x, y){
            ifelse(x > 0, y, NA)
        }, ., names(.))} 

#%>%
#        unlist(use.names = FALSE)

}


list2tags <- function(data, ncol = length(unique(na.omit(unlist(data))))){

    `%>%` <- dplyr::`%>%`

    lapply(data, function(x){
            x %>%
                matrix(ncol = ncol) %>%
                as.data.frame()
        }) %>%
        dplyr::bind_rows() %>%
        {Map(function(x){

            stats::setNames(tibble(x = ifelse(is.na(x), 0L, 1L)), unique(na.omit(x)) )

        }, .)} %>%
        dplyr::bind_cols()

}


library(dplyr)
data.frame(matrix(sample(0:1, 100, T), ncol = 10)) %>%
    tags2list()


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant