I have this piece of code that i need to make as a for loop. This code only works for GroupA, and I have a lot of Groups (grouoA, groupB, groupC etc.) - how can i make it into a function/foor loop so it makes a table for all my groups
dt <- data.table(ID = c(1, 2, 3, 4),
sex= c('F', 'M', 'F', 'F'),
education = c("A", "B", "C", "D"),
age = c(23, 34, 55, 77),
groupA= c(1, 5, 2, 4),
groupB= c(2, 3, 4, 3),
groupC= c(3, 1, 2, 4),
groupD= c(2, 3, 1, 3),
groupE= c(3, 5, 2, 4)
)
dt[, {
x=as.character(groupA)
x[is.na(groupA)]='Missing'
values <- unique(x)
foreach(v = values, .combine = rbind)%do%){
out=data.table(group = "groupA",
N = sum(x == v),
mean = sum(x==v)/.N))
out
}}]
Expected output is a table with;
group N mean
groupA 1 x (a number)
groupBetc 1 x (a number)