new column with paste0 in RHow to sort a dataframe by multiple column(s)Drop data frame columns by nameChecking conditions and adding items to a data frameCreating a column that has the count of elements of different columnmatching if string values are equal, creating a new string value in new column in RExtracting last word from many data frame columns (R)Replace column values with mean y by factor in third columnReplace values if two columns match in RReplace multiple words in R easily; str_replace_all gives error that two objects are not equal lengthsAdding constant to dataframe column conditional on other column

Should the Product Owner dictate what info the UI needs to display?

Apply a different color ramp to subset of categorized symbols in QGIS?

Is Electric Central Heating worth it if using Solar Panels?

Restricting the options of a lookup field, based on the value of another lookup field?

Why didn't the Space Shuttle bounce back into space as many times as possible so as to lose a lot of kinetic energy up there?

Are there moral objections to a life motivated purely by money? How to sway a person from this lifestyle?

What is the most expensive material in the world that could be used to create Pun-Pun's lute?

Is there any pythonic way to find average of specific tuple elements in array?

How do I deal with a coworker that keeps asking to make small superficial changes to a report, and it is seriously triggering my anxiety?

Check if a string is entirely made of the same substring

What is the best way to deal with NPC-NPC combat?

How do I check if a string is entirely made of the same substring?

Why do distances seem to matter in the Foundation world?

How much of a wave function must reside inside event horizon for it to be consumed by the black hole?

Multiple fireplaces in an apartment building?

Is Diceware more secure than a long passphrase?

Why do games have consumables?

Philosophical question on logistic regression: why isn't the optimal threshold value trained?

Retract an already submitted recommendation letter (written for an undergrad student)

What is the term for a person whose job is to place products on shelves in stores?

How to find if a column is referenced in a computed column?

Why is the underscore command _ useful?

My bank got bought out, am I now going to have to start filing tax returns in a different state?

I preordered a game on my Xbox while on the home screen of my friend's account. Which of us owns the game?



new column with paste0 in R


How to sort a dataframe by multiple column(s)Drop data frame columns by nameChecking conditions and adding items to a data frameCreating a column that has the count of elements of different columnmatching if string values are equal, creating a new string value in new column in RExtracting last word from many data frame columns (R)Replace column values with mean y by factor in third columnReplace values if two columns match in RReplace multiple words in R easily; str_replace_all gives error that two objects are not equal lengthsAdding constant to dataframe column conditional on other column






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I am looking for a function that allows me to add a new column to add the values called ID to a string, that is:



I have a list of words with your ID:



car = 9112
red = 9512
employee = 6117
sky = 2324

words<- c("car", "sky", "red", "employee", "domestic")
match<- c("car", "red", "domestic", "employee", "sky")


the comparison is made by reading in an excel file, if it finds the value equal to my vector words, it replaces the word with its ID, but leaves the original word



 x10<- c(words)# string

words.corpus <- c(L4$`match`) # pattern
idwords.corpus <- c(L4$`ID`) # replace
words.corpus <- paste0("\A",idwords.corpus, "\z|\A", words.corpus,"\z")

vect.corpus <- idwords.corpus
names(vect.corpus) <- words.corpus

data15 <- str_replace_all(x10, vect.corpus)


result:



data15:



" 9112", "2324", "9512", "6117", "employee"


What I'm looking for is to add a new column with the ID, instead of replacing the word with the ID



words ID
car 9112
red 9512
employee 6117
sky 2324
domestic domestic









share|improve this question






















  • difficult to help you fully without more info. But you could use a data.frame or data.table. data15 <- cbind(x10,ID=str_replace_all(x10, vect.corpus))

    – DJJ
    Mar 22 at 16:55

















0















I am looking for a function that allows me to add a new column to add the values called ID to a string, that is:



I have a list of words with your ID:



car = 9112
red = 9512
employee = 6117
sky = 2324

words<- c("car", "sky", "red", "employee", "domestic")
match<- c("car", "red", "domestic", "employee", "sky")


the comparison is made by reading in an excel file, if it finds the value equal to my vector words, it replaces the word with its ID, but leaves the original word



 x10<- c(words)# string

words.corpus <- c(L4$`match`) # pattern
idwords.corpus <- c(L4$`ID`) # replace
words.corpus <- paste0("\A",idwords.corpus, "\z|\A", words.corpus,"\z")

vect.corpus <- idwords.corpus
names(vect.corpus) <- words.corpus

data15 <- str_replace_all(x10, vect.corpus)


result:



data15:



" 9112", "2324", "9512", "6117", "employee"


What I'm looking for is to add a new column with the ID, instead of replacing the word with the ID



words ID
car 9112
red 9512
employee 6117
sky 2324
domestic domestic









share|improve this question






















  • difficult to help you fully without more info. But you could use a data.frame or data.table. data15 <- cbind(x10,ID=str_replace_all(x10, vect.corpus))

    – DJJ
    Mar 22 at 16:55













0












0








0








I am looking for a function that allows me to add a new column to add the values called ID to a string, that is:



I have a list of words with your ID:



car = 9112
red = 9512
employee = 6117
sky = 2324

words<- c("car", "sky", "red", "employee", "domestic")
match<- c("car", "red", "domestic", "employee", "sky")


the comparison is made by reading in an excel file, if it finds the value equal to my vector words, it replaces the word with its ID, but leaves the original word



 x10<- c(words)# string

words.corpus <- c(L4$`match`) # pattern
idwords.corpus <- c(L4$`ID`) # replace
words.corpus <- paste0("\A",idwords.corpus, "\z|\A", words.corpus,"\z")

vect.corpus <- idwords.corpus
names(vect.corpus) <- words.corpus

data15 <- str_replace_all(x10, vect.corpus)


result:



data15:



" 9112", "2324", "9512", "6117", "employee"


What I'm looking for is to add a new column with the ID, instead of replacing the word with the ID



words ID
car 9112
red 9512
employee 6117
sky 2324
domestic domestic









share|improve this question














I am looking for a function that allows me to add a new column to add the values called ID to a string, that is:



I have a list of words with your ID:



car = 9112
red = 9512
employee = 6117
sky = 2324

words<- c("car", "sky", "red", "employee", "domestic")
match<- c("car", "red", "domestic", "employee", "sky")


the comparison is made by reading in an excel file, if it finds the value equal to my vector words, it replaces the word with its ID, but leaves the original word



 x10<- c(words)# string

words.corpus <- c(L4$`match`) # pattern
idwords.corpus <- c(L4$`ID`) # replace
words.corpus <- paste0("\A",idwords.corpus, "\z|\A", words.corpus,"\z")

vect.corpus <- idwords.corpus
names(vect.corpus) <- words.corpus

data15 <- str_replace_all(x10, vect.corpus)


result:



data15:



" 9112", "2324", "9512", "6117", "employee"


What I'm looking for is to add a new column with the ID, instead of replacing the word with the ID



words ID
car 9112
red 9512
employee 6117
sky 2324
domestic domestic






r string tm






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 22 at 16:36









Max TCMax TC

325




325












  • difficult to help you fully without more info. But you could use a data.frame or data.table. data15 <- cbind(x10,ID=str_replace_all(x10, vect.corpus))

    – DJJ
    Mar 22 at 16:55

















  • difficult to help you fully without more info. But you could use a data.frame or data.table. data15 <- cbind(x10,ID=str_replace_all(x10, vect.corpus))

    – DJJ
    Mar 22 at 16:55
















difficult to help you fully without more info. But you could use a data.frame or data.table. data15 <- cbind(x10,ID=str_replace_all(x10, vect.corpus))

– DJJ
Mar 22 at 16:55





difficult to help you fully without more info. But you could use a data.frame or data.table. data15 <- cbind(x10,ID=str_replace_all(x10, vect.corpus))

– DJJ
Mar 22 at 16:55












1 Answer
1






active

oldest

votes


















0














I'd use data.table for fast lookup based on the fixed words value. While it's not 100% clear what you are asking for, it sounds like you want to replace words with an index value if there is a match, or leave the word as a word if not. This code will do that:





library("data.table")

# associate your ids with fixed word matches in a named numeric vector
ids <- data.table(
word = c("car", "red", "employee", "sky"),
ID = c(9112, 9512, 6117, 2324)
)
setkey(ids, word)

# this is what you would read in
data <- data.table(
word = c("car", "sky", "red", "employee", "domestic", "sky")
)
setkey(data, word)

data <- ids[data]
# replace NAs from no match with word
data[, ID := ifelse(is.na(ID), word, ID)]

data
## word ID
## 1: car 9112
## 2: domestic domestic
## 3: employee 6117
## 4: red 9512
## 5: sky 2324
## 6: sky 2324


Here the "domestic" is not matched so it remains as the word in the ID column. I also repeated "sky" to show how this will work for every instance of a word.



If you want to preserve the original sort order, you could create an index variable before the merge, and then reorder the output by that index variable.






share|improve this answer























    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%2f55304114%2fnew-column-with-paste0-in-r%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    I'd use data.table for fast lookup based on the fixed words value. While it's not 100% clear what you are asking for, it sounds like you want to replace words with an index value if there is a match, or leave the word as a word if not. This code will do that:





    library("data.table")

    # associate your ids with fixed word matches in a named numeric vector
    ids <- data.table(
    word = c("car", "red", "employee", "sky"),
    ID = c(9112, 9512, 6117, 2324)
    )
    setkey(ids, word)

    # this is what you would read in
    data <- data.table(
    word = c("car", "sky", "red", "employee", "domestic", "sky")
    )
    setkey(data, word)

    data <- ids[data]
    # replace NAs from no match with word
    data[, ID := ifelse(is.na(ID), word, ID)]

    data
    ## word ID
    ## 1: car 9112
    ## 2: domestic domestic
    ## 3: employee 6117
    ## 4: red 9512
    ## 5: sky 2324
    ## 6: sky 2324


    Here the "domestic" is not matched so it remains as the word in the ID column. I also repeated "sky" to show how this will work for every instance of a word.



    If you want to preserve the original sort order, you could create an index variable before the merge, and then reorder the output by that index variable.






    share|improve this answer



























      0














      I'd use data.table for fast lookup based on the fixed words value. While it's not 100% clear what you are asking for, it sounds like you want to replace words with an index value if there is a match, or leave the word as a word if not. This code will do that:





      library("data.table")

      # associate your ids with fixed word matches in a named numeric vector
      ids <- data.table(
      word = c("car", "red", "employee", "sky"),
      ID = c(9112, 9512, 6117, 2324)
      )
      setkey(ids, word)

      # this is what you would read in
      data <- data.table(
      word = c("car", "sky", "red", "employee", "domestic", "sky")
      )
      setkey(data, word)

      data <- ids[data]
      # replace NAs from no match with word
      data[, ID := ifelse(is.na(ID), word, ID)]

      data
      ## word ID
      ## 1: car 9112
      ## 2: domestic domestic
      ## 3: employee 6117
      ## 4: red 9512
      ## 5: sky 2324
      ## 6: sky 2324


      Here the "domestic" is not matched so it remains as the word in the ID column. I also repeated "sky" to show how this will work for every instance of a word.



      If you want to preserve the original sort order, you could create an index variable before the merge, and then reorder the output by that index variable.






      share|improve this answer

























        0












        0








        0







        I'd use data.table for fast lookup based on the fixed words value. While it's not 100% clear what you are asking for, it sounds like you want to replace words with an index value if there is a match, or leave the word as a word if not. This code will do that:





        library("data.table")

        # associate your ids with fixed word matches in a named numeric vector
        ids <- data.table(
        word = c("car", "red", "employee", "sky"),
        ID = c(9112, 9512, 6117, 2324)
        )
        setkey(ids, word)

        # this is what you would read in
        data <- data.table(
        word = c("car", "sky", "red", "employee", "domestic", "sky")
        )
        setkey(data, word)

        data <- ids[data]
        # replace NAs from no match with word
        data[, ID := ifelse(is.na(ID), word, ID)]

        data
        ## word ID
        ## 1: car 9112
        ## 2: domestic domestic
        ## 3: employee 6117
        ## 4: red 9512
        ## 5: sky 2324
        ## 6: sky 2324


        Here the "domestic" is not matched so it remains as the word in the ID column. I also repeated "sky" to show how this will work for every instance of a word.



        If you want to preserve the original sort order, you could create an index variable before the merge, and then reorder the output by that index variable.






        share|improve this answer













        I'd use data.table for fast lookup based on the fixed words value. While it's not 100% clear what you are asking for, it sounds like you want to replace words with an index value if there is a match, or leave the word as a word if not. This code will do that:





        library("data.table")

        # associate your ids with fixed word matches in a named numeric vector
        ids <- data.table(
        word = c("car", "red", "employee", "sky"),
        ID = c(9112, 9512, 6117, 2324)
        )
        setkey(ids, word)

        # this is what you would read in
        data <- data.table(
        word = c("car", "sky", "red", "employee", "domestic", "sky")
        )
        setkey(data, word)

        data <- ids[data]
        # replace NAs from no match with word
        data[, ID := ifelse(is.na(ID), word, ID)]

        data
        ## word ID
        ## 1: car 9112
        ## 2: domestic domestic
        ## 3: employee 6117
        ## 4: red 9512
        ## 5: sky 2324
        ## 6: sky 2324


        Here the "domestic" is not matched so it remains as the word in the ID column. I also repeated "sky" to show how this will work for every instance of a word.



        If you want to preserve the original sort order, you could create an index variable before the merge, and then reorder the output by that index variable.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 26 at 5:17









        Ken BenoitKen Benoit

        7,7081635




        7,7081635





























            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%2f55304114%2fnew-column-with-paste0-in-r%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문서를 완성해