Home > Net >  map function in R in data.table
map function in R in data.table

Time:08-21

I must be missing something, but I don't understand why my map function is not working.

I have a small data set, to which I want to append a ned column - sum of two existing columns:

DT <- data.table("columnPred" = c(1,2,3), 
                 "column1" = c(7,8,9), 
                 "column2" = c(44,55,66), 
                 "new_column1" = rep(NA, 3))

I wrote my function to sum up:

test_map <- function(x){
  
  x$new_column1 = x$column1   x$column2
  
}

and run map:

map(DT, test_map)

I keep getting errors. What is wrong with my map function? How can I use map to repeat the same function row-wise? is there a better alterntive

CodePudding user response:

We do not need map for that:

library(data.table)

DT[,new_column1 := (column1   column2)][]

#>    columnPred column1 column2 new_column1
#> 1:          1       7      44          51
#> 2:          2       8      55          63
#> 3:          3       9      66          75

However, if we want a map function to get the sum of the two columns, we can do the following:

library(data.table)
library(purrr)

pmap_dbl(DT, ~ ..2   ..3)

#> [1] 51 63 75

CodePudding user response:

We could use rowSums( which would also take care of NA elements if present)

library(data.table)
DT[, new_column1 := rowSums(.SD, na.rm = TRUE), .SDcols = column1:column2]

-output

> DT
   columnPred column1 column2 new_column1
        <num>   <num>   <num>       <num>
1:          1       7      44          51
2:          2       8      55          63
3:          3       9      66          75
  • Related