1

I have a matrix, and I am attempting to add a column at the end with the row sums, and then dividing the rows by the row sums, conditional on the row sum being greater than 100. This is what I have so far:

row.sums <- rowSums(a)
a <- cbind(a, row.sums)

This gives me the initial matrix I want, with a column at the end with the row Sums. The following code is what I have attempted for the second step:

a[(a[,dim(a)]>100)] <- dtm/row.sums

This gives me an error saying that the size of the vector I want to replace does not match the vector I want to replace it with. What am I doing wrong here? Sorry if this is a very basic question, I am pretty new to R/ coding in general.

Cin Sb Sangpi
  • 687
  • 3
  • 7
  • 22
Learning_R
  • 609
  • 1
  • 6
  • 11
  • You get the error because `row.sums` contains the sums for all rows, but you are trying to assign these to a smaller subset of the matrix only. So filter as well when creating `row.sums` – Christian Borck Sep 30 '15 at 13:19

1 Answers1

0

This maybe a bit lengthy solution , but it works.

df <- cbind(df, rowSums(df))
a <- 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)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213