Reputation: 25
I am working in R studio and I have a dataset such as: (the letters stand for the column names)
a b c d e f
0 1 3 1 0 1
3 1 0 4 1 2
0 1 0 0 3 4
I want to divide all values by the f-value corresponding to their column. So that would mean every value in the first row has to be divided by 1, every value in the second row by two and every value in the third row by 4.
i ve tried it like this:
#divide every number through sum variable of their row
my_matched_matrix = as.matrix(my_matched)
#making a vector out of sum row
avector <- as.vector(my_matched['sum'])
#sweep
sweeped <- sweep(mat,avector, `/`)
it gives me this error:
Error in dims[MARGIN] : invalid subscript type 'list'
Does anyone have an idea if there is any other way of getting where i want?
Upvotes: 0
Views: 1382
Reputation: 4768
Is this what you're looking for?
df <- read.table(text = "a b c d e f
0 1 3 1 0 1
3 1 0 4 1 2
0 1 0 0 3 4",
header = TRUE, stringsAsFactors = FALSE
df / df$f
Which returns:
a b c d e f
1 0.0 1.00 3 1 0.00 1
2 1.5 0.50 0 2 0.50 1
3 0.0 0.25 0 0 0.75 1
If you want this to print a little nicer you could do this:
x <- df / df$f
format(x, nsmall = 2)
a b c d e f
1 0.00 1.00 3.00 1.00 0.00 1.00
2 1.50 0.50 0.00 2.00 0.50 1.00
3 0.00 0.25 0.00 0.00 0.75 1.00
Upvotes: 1