r - Data Manipulation, Looping to add columns -
i have asked question couple times without help. have since improved code hoping has ideas! have dataset full of 0's , 1's. want add 10 columns resulting in 1 column 3835 rows. code far:
# select valid ids data = history[history$studyid %in% valid$studyid,] sibling = data[,c('b16aa','b16ba','b16ca','b16da','b16ea','b16fa','b16ga','b16ha','b16ia','b16ja')] # replace na values 0 sibling[is.na(sibling)] <- 0 # loop on columns , count number of 174 apply(sibling, 2, function(x) sum(x==174)) the problem code adds rows, want add columns result 1 column. answer getting wrong:
b16aa b16ba b16ca b16da b16ea b16fa b16ga b16ha b16ia b16ja 68 36 22 18 9 5 6 5 4 1
in apply() have margin set 2, columns. set margin argument 1, function, sum, applied across rows. mentioned @sgibb.
if doesn't work (can't reproduce example), try first converting elements of matrix integers x2 <- apply(sibling, c(1,2), function(x) x==174), , use rowsums add columns in each row: xsum <- rowsums(x2, na.rm=true). setup not need first change na's 0's, can handle na's na.rm argument in rowsums()
Comments
Post a Comment