I have a large data frame with columns that are a character string of numbers such as \"1, 2, 3, 4\". I wish to add a new column that is the average of these numbers. I have
library(data.table) cols <- paste0("a",1:4) setDT(df)[, (cols) := tstrsplit(a, ",", fixed=TRUE, type.convert=TRUE) ][, .(Mean = rowMeans(.SD)), .SDcols = cols] Mean 1: 2.5 2: 5.0 3: 7.5
Alternatively,
rowMeans(setDT(tstrsplit(df$a, ",", fixed=TRUE, type.convert=TRUE))) # [1] 2.5 5.0 7.5