我想將列添加到數據幀,通過因素看起來是這個樣子的相對頻率添加相對頻率(VAR2)由係數數據幀
X = structure(list(Var1 = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L,
8L, 9L, 10L, 11L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L
), .Label = c("0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"10"), class = "factor"), Var2 = structure(c(1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L), .Label = c("No Treatment", "Any Treatment"), class = "factor"),
Freq = c(1L, 3L, 6L, 13L, 30L, 53L, 69L, 123L, 198L, 270L,
1324L, 1L, 0L, 4L, 10L, 16L, 33L, 44L, 75L, 113L, 159L, 630L
)), .Names = c("Var1", "Var2", "Freq"), row.names = c(NA,
-22L), class = "data.frame")
,我心目中是該解決方案非常複雜,而且不太靈活。這是我在做什麼現在:
library(data.table)
DT =data.table(X)
myfun <- function (freq, group, total1, total2)
{
if(group[[1]] == "No Treatment"){
relfreq = freq/total1
}else{
relfreq = freq/total2
}
return(relfreq)
}
DT[,relfreq:=myfun(Freq,Var2,sum(DT$Freq[DT$Var2=="No Treatment"]), sum(DT$Freq[DT$Var2=="Any Treatment"]))]
有人能告訴我一個更好的解決方案更加靈活,允許VAR2以超過2個值?
謝謝!
+1用於提供可重現的示例,並使用'structure(...)'提供樣本數據。 – jlhoward