I am using data.table I have a vector of the names for the new columns. I want to create these new columns but using the information from the old columns. Let me show it on a following example:
data <- data.table(a = c("OneA", "TwoB", "ThreeC"),
b = c(1, 2, 3))
newCols <- c("One", "Two", "Three")
for (newCol in newCols) {
data[, eval(newCol) := gsub(paste0("^.*", newCol), "", a)]
}
As an output I expect (and get) the following:
> data
a b One Two Three
1: OneA 1 A OneA OneA
2: TwoB 2 TwoB B TwoB
3: ThreeC 3 ThreeC ThreeC C
In this case I combine defining new columns from the vector and using the vector values themselves to fill these columns. Is there a way to do it more optimal (for example with a set())?
One possible approach could be:
library(data.table)
DT[, (newCols) := lapply(newCols, function(x) sub(x, "", a))][]
#> a b One Two Three
#> 1: OneA 1 A OneA OneA
#> 2: TwoB 2 TwoB B TwoB
#> 3: ThreeC 3 ThreeC ThreeC C
Data
DT <- data.table(a = c("OneA", "TwoB", "ThreeC"), b = c(1, 2, 3))
newCols <- c("One", "Two", "Three")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With