Group Values Based on Vector and Update ColumnHow to access the last value in a vector?Test if a vector contains a given elementHow to sort a dataframe by multiple column(s)Counting the number of elements with the values of x in a vectorGrouping functions (tapply, by, aggregate) and the *apply familyDrop data frame columns by nameRemove rows with all or some NAs (missing values) in data.frameGroup by multiple columns in dplyr, using string vector inputExtract a dplyr tbl column as a vectorgsub error message when addressing column in dataframe in RStudio

How to win against ants

A Haskell implementation of Conway's Game of Life, viewable on the console, no external libs

Repeated! Factorials!

If someone else uploads my GPL'd code to Github without my permission, is that a copyright violation?

Pronouns when writing from the point of view of a robot

Is there a general term for the items in a directory?

What is the difference between get_permalink vs get_the_permalink?

How can I perform a deterministic physics simulation?

In MTG, was there ever a five-color deck that worked well?

Can a Hogwarts student refuse the Sorting Hat's decision?

What printing process is this?

Based on what criteria do you add/not add icons to labels within a toolbar?

What is a Written Word™?

Why is the Vasa Museum in Stockholm so Popular?

What could prevent players from leaving an island?

What does Argus Filch specifically do?

conditional probability of dependent random variables

Formal mathematical definition of renormalization group flow

How long should I wait to plug in my refrigerator after unplugging it?

How to design an effective polearm-bow hybrid?

Generate random number in Unity without class ambiguity

Does a humanoid possessed by a ghost register as undead to a paladin's Divine Sense?

Has J.J.Jameson ever found out that Peter Parker is Spider-Man?

What's "halachic" about "Esav hates Ya'akov"?



Group Values Based on Vector and Update Column


How to access the last value in a vector?Test if a vector contains a given elementHow to sort a dataframe by multiple column(s)Counting the number of elements with the values of x in a vectorGrouping functions (tapply, by, aggregate) and the *apply familyDrop data frame columns by nameRemove rows with all or some NAs (missing values) in data.frameGroup by multiple columns in dplyr, using string vector inputExtract a dplyr tbl column as a vectorgsub error message when addressing column in dataframe in RStudio






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I'm trying to group various values based on a predefined vector and then update a column.



Sample Data



df <- data.frame(ID = 1:5, Type = c("Windows", "Windows Server", "Cat", "Dog", "Eggs"))

it <- c("Windows", "Windows Server")
animal <- c("Cat", "Dog")
food <- c("Eggs")


What I tried but failed



df$Grouping <- gsub(it, "IT", df$Type)



Error: Pattern > 1




Method that works but long-winded



Using dplyr mutate, I'll be able to achieve what I want but it is very long winded as I have multiple elements in a vector.



df %>% mutate(Grouping = ifelse(Type == "Windows", "IT", 
ifelse ...))


Intended Output



ID Type Grouping
1 1 Windows IT
2 2 Windows Server IT
3 3 Cat Animal
4 4 Dog Animal
5 5 Eggs Food


Thanks!










share|improve this question
























  • Create dataframe and merge back ?

    – WeNYoBen
    Mar 27 at 2:39











  • Your gsub is failing because you're providing a vector as the search-for expression. It will work if you do: gsub(paste(it, collapse = "|"), "IT", c("Windows", "Windows Server", "Cat", "Dog", "Eggs"))

    – PavoDive
    Mar 27 at 3:13











  • @PavoDive that's really helpful, thank you!

    – Javier
    Mar 27 at 7:56

















1















I'm trying to group various values based on a predefined vector and then update a column.



Sample Data



df <- data.frame(ID = 1:5, Type = c("Windows", "Windows Server", "Cat", "Dog", "Eggs"))

it <- c("Windows", "Windows Server")
animal <- c("Cat", "Dog")
food <- c("Eggs")


What I tried but failed



df$Grouping <- gsub(it, "IT", df$Type)



Error: Pattern > 1




Method that works but long-winded



Using dplyr mutate, I'll be able to achieve what I want but it is very long winded as I have multiple elements in a vector.



df %>% mutate(Grouping = ifelse(Type == "Windows", "IT", 
ifelse ...))


Intended Output



ID Type Grouping
1 1 Windows IT
2 2 Windows Server IT
3 3 Cat Animal
4 4 Dog Animal
5 5 Eggs Food


Thanks!










share|improve this question
























  • Create dataframe and merge back ?

    – WeNYoBen
    Mar 27 at 2:39











  • Your gsub is failing because you're providing a vector as the search-for expression. It will work if you do: gsub(paste(it, collapse = "|"), "IT", c("Windows", "Windows Server", "Cat", "Dog", "Eggs"))

    – PavoDive
    Mar 27 at 3:13











  • @PavoDive that's really helpful, thank you!

    – Javier
    Mar 27 at 7:56













1












1








1








I'm trying to group various values based on a predefined vector and then update a column.



Sample Data



df <- data.frame(ID = 1:5, Type = c("Windows", "Windows Server", "Cat", "Dog", "Eggs"))

it <- c("Windows", "Windows Server")
animal <- c("Cat", "Dog")
food <- c("Eggs")


What I tried but failed



df$Grouping <- gsub(it, "IT", df$Type)



Error: Pattern > 1




Method that works but long-winded



Using dplyr mutate, I'll be able to achieve what I want but it is very long winded as I have multiple elements in a vector.



df %>% mutate(Grouping = ifelse(Type == "Windows", "IT", 
ifelse ...))


Intended Output



ID Type Grouping
1 1 Windows IT
2 2 Windows Server IT
3 3 Cat Animal
4 4 Dog Animal
5 5 Eggs Food


Thanks!










share|improve this question














I'm trying to group various values based on a predefined vector and then update a column.



Sample Data



df <- data.frame(ID = 1:5, Type = c("Windows", "Windows Server", "Cat", "Dog", "Eggs"))

it <- c("Windows", "Windows Server")
animal <- c("Cat", "Dog")
food <- c("Eggs")


What I tried but failed



df$Grouping <- gsub(it, "IT", df$Type)



Error: Pattern > 1




Method that works but long-winded



Using dplyr mutate, I'll be able to achieve what I want but it is very long winded as I have multiple elements in a vector.



df %>% mutate(Grouping = ifelse(Type == "Windows", "IT", 
ifelse ...))


Intended Output



ID Type Grouping
1 1 Windows IT
2 2 Windows Server IT
3 3 Cat Animal
4 4 Dog Animal
5 5 Eggs Food


Thanks!







r dplyr






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 27 at 2:34









JavierJavier

4412 silver badges12 bronze badges




4412 silver badges12 bronze badges















  • Create dataframe and merge back ?

    – WeNYoBen
    Mar 27 at 2:39











  • Your gsub is failing because you're providing a vector as the search-for expression. It will work if you do: gsub(paste(it, collapse = "|"), "IT", c("Windows", "Windows Server", "Cat", "Dog", "Eggs"))

    – PavoDive
    Mar 27 at 3:13











  • @PavoDive that's really helpful, thank you!

    – Javier
    Mar 27 at 7:56

















  • Create dataframe and merge back ?

    – WeNYoBen
    Mar 27 at 2:39











  • Your gsub is failing because you're providing a vector as the search-for expression. It will work if you do: gsub(paste(it, collapse = "|"), "IT", c("Windows", "Windows Server", "Cat", "Dog", "Eggs"))

    – PavoDive
    Mar 27 at 3:13











  • @PavoDive that's really helpful, thank you!

    – Javier
    Mar 27 at 7:56
















Create dataframe and merge back ?

– WeNYoBen
Mar 27 at 2:39





Create dataframe and merge back ?

– WeNYoBen
Mar 27 at 2:39













Your gsub is failing because you're providing a vector as the search-for expression. It will work if you do: gsub(paste(it, collapse = "|"), "IT", c("Windows", "Windows Server", "Cat", "Dog", "Eggs"))

– PavoDive
Mar 27 at 3:13





Your gsub is failing because you're providing a vector as the search-for expression. It will work if you do: gsub(paste(it, collapse = "|"), "IT", c("Windows", "Windows Server", "Cat", "Dog", "Eggs"))

– PavoDive
Mar 27 at 3:13













@PavoDive that's really helpful, thank you!

– Javier
Mar 27 at 7:56





@PavoDive that's really helpful, thank you!

– Javier
Mar 27 at 7:56












3 Answers
3






active

oldest

votes


















0














One option would be to create a list (or a data.frame) for the mappings and then do a left_join



map <- list(
it = c("Windows", "Windows Server"),
animal = c("Cat", "Dog"),
food = c("Eggs"))

library(dplyr)
df %>% left_join(stack(map), by = c("Type" = "values"))
# ID Type ind
#1 1 Windows it
#2 2 Windows Server it
#3 3 Cat animal
#4 4 Dog animal
#5 5 Eggs food





share|improve this answer

























  • Thanks for the solution, this works perfectly! I have a question though. Do you know why when I define my vectors outside of the list, the stack(map) does not seem to work? It shows me this error: Error in data.frame(values = unlist(unname(x)), ind, stringsAsFactors = FALSE) : arguments imply differing number of rows: 5, 0

    – Javier
    Mar 27 at 2:57











  • @Javier "Do you know why when I define my vectors outside of the list, the stack(map) does not seem to work?" I don't know what that means? Why "outside of the list"? You need to define a list with named elements. stack then row-stacks the entries from every list element in column values and then adds a column ind to indicate from which element they came.

    – Maurits Evers
    Mar 27 at 3:00












  • Ah i didn't know the list has to have named elements for stack to work. Thanks so much!

    – Javier
    Mar 27 at 3:01


















1














Create a list of your predefined vectors and then check which element of the list has the items inside the df$Type



mylist = mget(c("animal", "food", "it"))
names(mylist)[max.col(t(sapply(df$Type, function(x) lapply(mylist, function(y) x %in% y))))]
#[1] "it" "it" "animal" "animal" "food"





share|improve this answer


































    0














    the question as posted doesn't make a lot of sense. Specifically, with the sample data, Its no simpler to to store the independent type vectors than to store the the type as an attribute of the initial data frame. maybe you could add some color that gives more detail about the nature of the problem.



    with that said, assuming your problem is that the lookup vectors are stored in a different source and need to be loaded independently, a simple loop should suffice. (I'm using data.table, cause i don't even remember how to use a raw data.frame anymore):



    df <- data.table(ID = 1:5, Type = c("Windows", "Windows Server", "Cat", "Dog", "Eggs"))
    it <- c("Windows", "Windows Server")
    animal <- c("Cat", "Dog")
    food <- c("Eggs")

    lookup.names <- c("it", "animal", "food")
    for (z in 1:length(lookup.names) )
    lookup <- get(lookup.names[z]) #maybe need to do some more sophisticated load, like from a file or database
    df[Type %in% lookup, Grouping := lookup.names[z]]






    share|improve this answer

























    • Hi, the question posted is a watered down, reproducible example of my problem. A loop may not be as efficient as I'm dealing with a big data set; hence using a left_join as provided by the other users works better

      – Javier
      Mar 27 at 7:59













    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55368940%2fgroup-values-based-on-vector-and-update-column%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    One option would be to create a list (or a data.frame) for the mappings and then do a left_join



    map <- list(
    it = c("Windows", "Windows Server"),
    animal = c("Cat", "Dog"),
    food = c("Eggs"))

    library(dplyr)
    df %>% left_join(stack(map), by = c("Type" = "values"))
    # ID Type ind
    #1 1 Windows it
    #2 2 Windows Server it
    #3 3 Cat animal
    #4 4 Dog animal
    #5 5 Eggs food





    share|improve this answer

























    • Thanks for the solution, this works perfectly! I have a question though. Do you know why when I define my vectors outside of the list, the stack(map) does not seem to work? It shows me this error: Error in data.frame(values = unlist(unname(x)), ind, stringsAsFactors = FALSE) : arguments imply differing number of rows: 5, 0

      – Javier
      Mar 27 at 2:57











    • @Javier "Do you know why when I define my vectors outside of the list, the stack(map) does not seem to work?" I don't know what that means? Why "outside of the list"? You need to define a list with named elements. stack then row-stacks the entries from every list element in column values and then adds a column ind to indicate from which element they came.

      – Maurits Evers
      Mar 27 at 3:00












    • Ah i didn't know the list has to have named elements for stack to work. Thanks so much!

      – Javier
      Mar 27 at 3:01















    0














    One option would be to create a list (or a data.frame) for the mappings and then do a left_join



    map <- list(
    it = c("Windows", "Windows Server"),
    animal = c("Cat", "Dog"),
    food = c("Eggs"))

    library(dplyr)
    df %>% left_join(stack(map), by = c("Type" = "values"))
    # ID Type ind
    #1 1 Windows it
    #2 2 Windows Server it
    #3 3 Cat animal
    #4 4 Dog animal
    #5 5 Eggs food





    share|improve this answer

























    • Thanks for the solution, this works perfectly! I have a question though. Do you know why when I define my vectors outside of the list, the stack(map) does not seem to work? It shows me this error: Error in data.frame(values = unlist(unname(x)), ind, stringsAsFactors = FALSE) : arguments imply differing number of rows: 5, 0

      – Javier
      Mar 27 at 2:57











    • @Javier "Do you know why when I define my vectors outside of the list, the stack(map) does not seem to work?" I don't know what that means? Why "outside of the list"? You need to define a list with named elements. stack then row-stacks the entries from every list element in column values and then adds a column ind to indicate from which element they came.

      – Maurits Evers
      Mar 27 at 3:00












    • Ah i didn't know the list has to have named elements for stack to work. Thanks so much!

      – Javier
      Mar 27 at 3:01













    0












    0








    0







    One option would be to create a list (or a data.frame) for the mappings and then do a left_join



    map <- list(
    it = c("Windows", "Windows Server"),
    animal = c("Cat", "Dog"),
    food = c("Eggs"))

    library(dplyr)
    df %>% left_join(stack(map), by = c("Type" = "values"))
    # ID Type ind
    #1 1 Windows it
    #2 2 Windows Server it
    #3 3 Cat animal
    #4 4 Dog animal
    #5 5 Eggs food





    share|improve this answer













    One option would be to create a list (or a data.frame) for the mappings and then do a left_join



    map <- list(
    it = c("Windows", "Windows Server"),
    animal = c("Cat", "Dog"),
    food = c("Eggs"))

    library(dplyr)
    df %>% left_join(stack(map), by = c("Type" = "values"))
    # ID Type ind
    #1 1 Windows it
    #2 2 Windows Server it
    #3 3 Cat animal
    #4 4 Dog animal
    #5 5 Eggs food






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 27 at 2:41









    Maurits EversMaurits Evers

    33.4k4 gold badges19 silver badges38 bronze badges




    33.4k4 gold badges19 silver badges38 bronze badges















    • Thanks for the solution, this works perfectly! I have a question though. Do you know why when I define my vectors outside of the list, the stack(map) does not seem to work? It shows me this error: Error in data.frame(values = unlist(unname(x)), ind, stringsAsFactors = FALSE) : arguments imply differing number of rows: 5, 0

      – Javier
      Mar 27 at 2:57











    • @Javier "Do you know why when I define my vectors outside of the list, the stack(map) does not seem to work?" I don't know what that means? Why "outside of the list"? You need to define a list with named elements. stack then row-stacks the entries from every list element in column values and then adds a column ind to indicate from which element they came.

      – Maurits Evers
      Mar 27 at 3:00












    • Ah i didn't know the list has to have named elements for stack to work. Thanks so much!

      – Javier
      Mar 27 at 3:01

















    • Thanks for the solution, this works perfectly! I have a question though. Do you know why when I define my vectors outside of the list, the stack(map) does not seem to work? It shows me this error: Error in data.frame(values = unlist(unname(x)), ind, stringsAsFactors = FALSE) : arguments imply differing number of rows: 5, 0

      – Javier
      Mar 27 at 2:57











    • @Javier "Do you know why when I define my vectors outside of the list, the stack(map) does not seem to work?" I don't know what that means? Why "outside of the list"? You need to define a list with named elements. stack then row-stacks the entries from every list element in column values and then adds a column ind to indicate from which element they came.

      – Maurits Evers
      Mar 27 at 3:00












    • Ah i didn't know the list has to have named elements for stack to work. Thanks so much!

      – Javier
      Mar 27 at 3:01
















    Thanks for the solution, this works perfectly! I have a question though. Do you know why when I define my vectors outside of the list, the stack(map) does not seem to work? It shows me this error: Error in data.frame(values = unlist(unname(x)), ind, stringsAsFactors = FALSE) : arguments imply differing number of rows: 5, 0

    – Javier
    Mar 27 at 2:57





    Thanks for the solution, this works perfectly! I have a question though. Do you know why when I define my vectors outside of the list, the stack(map) does not seem to work? It shows me this error: Error in data.frame(values = unlist(unname(x)), ind, stringsAsFactors = FALSE) : arguments imply differing number of rows: 5, 0

    – Javier
    Mar 27 at 2:57













    @Javier "Do you know why when I define my vectors outside of the list, the stack(map) does not seem to work?" I don't know what that means? Why "outside of the list"? You need to define a list with named elements. stack then row-stacks the entries from every list element in column values and then adds a column ind to indicate from which element they came.

    – Maurits Evers
    Mar 27 at 3:00






    @Javier "Do you know why when I define my vectors outside of the list, the stack(map) does not seem to work?" I don't know what that means? Why "outside of the list"? You need to define a list with named elements. stack then row-stacks the entries from every list element in column values and then adds a column ind to indicate from which element they came.

    – Maurits Evers
    Mar 27 at 3:00














    Ah i didn't know the list has to have named elements for stack to work. Thanks so much!

    – Javier
    Mar 27 at 3:01





    Ah i didn't know the list has to have named elements for stack to work. Thanks so much!

    – Javier
    Mar 27 at 3:01













    1














    Create a list of your predefined vectors and then check which element of the list has the items inside the df$Type



    mylist = mget(c("animal", "food", "it"))
    names(mylist)[max.col(t(sapply(df$Type, function(x) lapply(mylist, function(y) x %in% y))))]
    #[1] "it" "it" "animal" "animal" "food"





    share|improve this answer































      1














      Create a list of your predefined vectors and then check which element of the list has the items inside the df$Type



      mylist = mget(c("animal", "food", "it"))
      names(mylist)[max.col(t(sapply(df$Type, function(x) lapply(mylist, function(y) x %in% y))))]
      #[1] "it" "it" "animal" "animal" "food"





      share|improve this answer





























        1












        1








        1







        Create a list of your predefined vectors and then check which element of the list has the items inside the df$Type



        mylist = mget(c("animal", "food", "it"))
        names(mylist)[max.col(t(sapply(df$Type, function(x) lapply(mylist, function(y) x %in% y))))]
        #[1] "it" "it" "animal" "animal" "food"





        share|improve this answer















        Create a list of your predefined vectors and then check which element of the list has the items inside the df$Type



        mylist = mget(c("animal", "food", "it"))
        names(mylist)[max.col(t(sapply(df$Type, function(x) lapply(mylist, function(y) x %in% y))))]
        #[1] "it" "it" "animal" "animal" "food"






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 27 at 2:59

























        answered Mar 27 at 2:47









        d.bd.b

        21.7k4 gold badges19 silver badges50 bronze badges




        21.7k4 gold badges19 silver badges50 bronze badges
























            0














            the question as posted doesn't make a lot of sense. Specifically, with the sample data, Its no simpler to to store the independent type vectors than to store the the type as an attribute of the initial data frame. maybe you could add some color that gives more detail about the nature of the problem.



            with that said, assuming your problem is that the lookup vectors are stored in a different source and need to be loaded independently, a simple loop should suffice. (I'm using data.table, cause i don't even remember how to use a raw data.frame anymore):



            df <- data.table(ID = 1:5, Type = c("Windows", "Windows Server", "Cat", "Dog", "Eggs"))
            it <- c("Windows", "Windows Server")
            animal <- c("Cat", "Dog")
            food <- c("Eggs")

            lookup.names <- c("it", "animal", "food")
            for (z in 1:length(lookup.names) )
            lookup <- get(lookup.names[z]) #maybe need to do some more sophisticated load, like from a file or database
            df[Type %in% lookup, Grouping := lookup.names[z]]






            share|improve this answer

























            • Hi, the question posted is a watered down, reproducible example of my problem. A loop may not be as efficient as I'm dealing with a big data set; hence using a left_join as provided by the other users works better

              – Javier
              Mar 27 at 7:59















            0














            the question as posted doesn't make a lot of sense. Specifically, with the sample data, Its no simpler to to store the independent type vectors than to store the the type as an attribute of the initial data frame. maybe you could add some color that gives more detail about the nature of the problem.



            with that said, assuming your problem is that the lookup vectors are stored in a different source and need to be loaded independently, a simple loop should suffice. (I'm using data.table, cause i don't even remember how to use a raw data.frame anymore):



            df <- data.table(ID = 1:5, Type = c("Windows", "Windows Server", "Cat", "Dog", "Eggs"))
            it <- c("Windows", "Windows Server")
            animal <- c("Cat", "Dog")
            food <- c("Eggs")

            lookup.names <- c("it", "animal", "food")
            for (z in 1:length(lookup.names) )
            lookup <- get(lookup.names[z]) #maybe need to do some more sophisticated load, like from a file or database
            df[Type %in% lookup, Grouping := lookup.names[z]]






            share|improve this answer

























            • Hi, the question posted is a watered down, reproducible example of my problem. A loop may not be as efficient as I'm dealing with a big data set; hence using a left_join as provided by the other users works better

              – Javier
              Mar 27 at 7:59













            0












            0








            0







            the question as posted doesn't make a lot of sense. Specifically, with the sample data, Its no simpler to to store the independent type vectors than to store the the type as an attribute of the initial data frame. maybe you could add some color that gives more detail about the nature of the problem.



            with that said, assuming your problem is that the lookup vectors are stored in a different source and need to be loaded independently, a simple loop should suffice. (I'm using data.table, cause i don't even remember how to use a raw data.frame anymore):



            df <- data.table(ID = 1:5, Type = c("Windows", "Windows Server", "Cat", "Dog", "Eggs"))
            it <- c("Windows", "Windows Server")
            animal <- c("Cat", "Dog")
            food <- c("Eggs")

            lookup.names <- c("it", "animal", "food")
            for (z in 1:length(lookup.names) )
            lookup <- get(lookup.names[z]) #maybe need to do some more sophisticated load, like from a file or database
            df[Type %in% lookup, Grouping := lookup.names[z]]






            share|improve this answer













            the question as posted doesn't make a lot of sense. Specifically, with the sample data, Its no simpler to to store the independent type vectors than to store the the type as an attribute of the initial data frame. maybe you could add some color that gives more detail about the nature of the problem.



            with that said, assuming your problem is that the lookup vectors are stored in a different source and need to be loaded independently, a simple loop should suffice. (I'm using data.table, cause i don't even remember how to use a raw data.frame anymore):



            df <- data.table(ID = 1:5, Type = c("Windows", "Windows Server", "Cat", "Dog", "Eggs"))
            it <- c("Windows", "Windows Server")
            animal <- c("Cat", "Dog")
            food <- c("Eggs")

            lookup.names <- c("it", "animal", "food")
            for (z in 1:length(lookup.names) )
            lookup <- get(lookup.names[z]) #maybe need to do some more sophisticated load, like from a file or database
            df[Type %in% lookup, Grouping := lookup.names[z]]







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 27 at 3:20









            EthanEthan

            16710 bronze badges




            16710 bronze badges















            • Hi, the question posted is a watered down, reproducible example of my problem. A loop may not be as efficient as I'm dealing with a big data set; hence using a left_join as provided by the other users works better

              – Javier
              Mar 27 at 7:59

















            • Hi, the question posted is a watered down, reproducible example of my problem. A loop may not be as efficient as I'm dealing with a big data set; hence using a left_join as provided by the other users works better

              – Javier
              Mar 27 at 7:59
















            Hi, the question posted is a watered down, reproducible example of my problem. A loop may not be as efficient as I'm dealing with a big data set; hence using a left_join as provided by the other users works better

            – Javier
            Mar 27 at 7:59





            Hi, the question posted is a watered down, reproducible example of my problem. A loop may not be as efficient as I'm dealing with a big data set; hence using a left_join as provided by the other users works better

            – Javier
            Mar 27 at 7:59

















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55368940%2fgroup-values-based-on-vector-and-update-column%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해