Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7808209
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T03:04:47+00:00 2026-06-02T03:04:47+00:00

I’d like to add a new column to my data.table, which contains data from

  • 0

I’d like to add a new column to my data.table, which contains data from one of the other columns. The choice of column, however, varies per row – depending on the contents of another column. So:

for the data set:

     a_data b_data column_choice
[1,]     55      1             a
[2,]     56      2             a
[3,]     57      3             b

generated by:

dat=data.table(a_data = c(55, 56, 57), 
               b_data = c(1,  2,  3), 
               column_choice = c("a", "a", "b"))

I’d like a new column, ‘chosen’, which contains (per row) either the data from “a_data” or “b_data”, depending on the value of “column_choice”. The resulting data table will therefore be:

     a_data b_data column_choice chosen
[1,]     55      1             a     55
[2,]     56      2             a     56
[3,]     57      3             b      3

I have managed to get the desired effect using:

dat=dat[, data.table(.SD, chosen=.SD[[paste0(.SD$column_choice, "_data")]]),
        by=1:nrow(a)]
dat$nrow = NULL

however this feels quite clunky; perhaps there’s a simpler way to do it (that will no doubt also teach me something about R)?

In practice, the data frame also has lots of other columns that need to be preserved, more choices than just ‘a or b’, and several of these types of column to generate, so I’d rather not use the basic ifelse solution that may be appropriate for the basic example above.

Thank you very much for your help.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T03:04:48+00:00Added an answer on June 2, 2026 at 3:04 am

    I think I’ve now found a properly vectorised one liner, that’s also faster than the other answers in this case.

    petesFun2 uses data.table aggregation as petesFun, however now vectorised across column_choice (rather than per item, as previously).

    While petesFun2 is fine for my purposes, it does leave both the rows and columns in a different order. In the interests of comparison with the other answers, therefore, I’ve added petesFun2Clean which maintains the same ordering as the other answers.

    petesFun2 <-function(myDat) {
      return(myDat[, cbind(.SD, chosen=.SD[[paste0(.BY$column_choice, "_data")]]),
                   by=column_choice])
    }
    
    petesFun2Clean <-function(myDat) {
      myDat = copy(myDat) # To prevent reference issues
      myDat[, id := seq_len(nrow(myDat))] # Assign an id
      result = myDat[, cbind(.SD, chosen=.SD[[.BY$choice]]),
                     by=list(column_choice, choice=paste0(column_choice, "_data"))]
    
      # recover ordering and column order.
      return(result[order(id), 
                    list(a_data, b_data, c_data, column_choice, chosen)]) 
    }
    
    benchmark(benRes<-   myFun(test.dat),
              petesRes<- petesFun(test.dat),
              dowleRes<- dowleFun(test.dat),
              petesRes2<-petesFun2(test.dat),
              petesRes2Clean<- petesFun2Clean(test.dat),
              replications=25,
              columns=c("test", "replications", "elapsed", "relative"))
    
    #                                         test replications elapsed  relative
    # 1                  benRes <- myFun(test.dat)           25   0.337  4.160494
    # 3             dowleRes <- dowleFun(test.dat)           25   0.191  2.358025
    # 5 petesRes2Clean <- petesFun2Clean(test.dat)           25   0.122  1.506173
    # 4           petesRes2 <- petesFun2(test.dat)           25   0.081  1.000000
    # 2             petesRes <- petesFun(test.dat)           25   4.018 49.604938
    
    identical(petesRes2, benRes)
    # FALSE (due to row and column ordering)
    identical(petesRes2Clean, benRes)
    # TRUE
    

    EDIT: I just noticed (as mentioned by Matthew in the comments) that we now have by group :=. So we can drop the cbind and simply do:

    myDat[, chosen := .SD[[paste0(.BY$column_choice, “_data”)]],
    by=column_choice]

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I would like to run a str_replace or preg_replace which looks for certain words
I have a text area in my form which accepts all possible characters from
I have some data like this: 1 2 3 4 5 9 2 6
I would like to count the length of a string with PHP. The string
I used javascript for loading a picture on my website depending on which small
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am trying to understand how to use SyndicationItem to display feed which is
I've got a string that has curly quotes in it. I'd like to replace

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.