How do I divide rows by the row sum and rows that meet a certain condition (row Sum >100)in matrix?r -
i have matrix, , attempting add column @ end row sums, , dividing rows row sums, conditional on row sum being greater 100. have far:
row.sums <- rowsums(a) <- cbind(a, row.sums)
this gives me initial matrix want, column @ end row sums. following code have attempted second step:
a[(a[,dim(a)]>100)] <- dtm/row.sums
this gives me error saying size of vector want replace not match vector want replace with. doing wrong here? sorry if basic question, pretty new r/ coding in general.
this maybe bit lengthy solution , works.
df <- cbind(df, rowsums(df)) <- df[, dim(df)[2]] for(i in 1:length(a)) { if(a[i] > 100) { df[i, ] <- df[i, ]/a } } #> df # [,1] [,2] [,3] [,4] [,5] [,6] [,7] # x 0.03333333 0.050 0.1000000 0.100 0.1666667 0.375 1.000000 # y 0.06666667 0.075 0.1333333 0.125 0.2000000 0.500 1.333333
data
x <- c(100,200,300,400,500) y <- c(200,300,400, 500, 600) df <- rbind(x, y)
Comments
Post a Comment