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.
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
x <- c(100,200,300,400,500)
y <- c(200,300,400, 500, 600)
df <- rbind(x, y)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.