D = c("d", "d", "S", "d")
A = c("d", "a", "a", "x")
X = c("v", "x", "x", "t")
R = c("t", "r", "r", "r")
dat = data.frame(D, A, X, R)
D A X R MajoritySum
d d v t 1
d a x r 4
s a x r 3
d x t r 2
I am currently trying to add the MajoritySum column pictured above which counts the number of times a row has a value that is in the majority of a factor level variable.
I looped through the dataframe to grab the majority class for each column but now having difficulty from here.
majority = rep(NA, 4)
for(i in c(1:4)){
majority[i] =
names(sort(table(dat[,i]),decreasing = TRUE)[1])
}
> majority
[1] "d" "a" "x" "r"