0

I have 5 columns, Units1, Units2, Units3, Units4, Units5. I am trying to create a new column say

master$Sales <- master$Units1

However, I want this Units1 to be dynamic such that Sales has the datatype of UnitsX.

My current solution created Sales as a list instead of double.

Sales_Variable <- "Units"
UnitsType <- x #which is 1 in this case
master$Sales <- master[names(master) == paste0(Sales_Variable,UnitsType)]

Please guide me on how I can solve this.

Thanks,

Ashutosh Deshpande

  • It sounds like you want _one_ column `Sales` to have the values of _five_ columns `Units1:Units5`; can you confirm that and expand on why you think that's necessary? – r2evans Dec 05 '22 at 17:53
  • @r2evans-GONAVYBEATARMY I am running various Iterations of a model, and each time I have to take a different column (there are 8 such columns), but keep the entire other code intact, thus Sales is a fixed column. – Ashutosh Deshpande Dec 05 '22 at 17:57
  • `master$Sales <- master[[ paste0(Sales_Variable, UnitsType) ]]`? – r2evans Dec 05 '22 at 18:00
  • If you're running different models/regression, you can also consider _not_ creating `Sales` each time, instead updating your formula such that `Units1` is removed from the RHS and replaces the previous LHS. – r2evans Dec 05 '22 at 18:01
  • Actually yes, i was doing this inside a for loop. Thanks a lot :-) – Ashutosh Deshpande Dec 05 '22 at 18:09
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Dec 05 '22 at 18:25

0 Answers0