Reputation: 13
I have a data frame
A B C D
r1 10 7 19 11
r2 5 5 7 8
r3 12 9 13 11
r4 8 10 11 9
I want to create 2 data frames whose values are:
min
value in row from each element of that row,min
value in column from each element of that column.I got function for column
d1=transform(d,A=A-(min(A)),B=B-(min(B)),C=C-(min(C)),D=D-(min(D)))
Result I get is is as below,
> d1
A B C D
r1 5 2 12 3
r2 0 0 0 0
r3 7 4 6 3
r4 3 5 4 1
what function I should use to get result for rows, which I want is
> d2
A B C D
r1 0 2 9 1
r2 0 5 2 3
r3 1 3 2 0
r4 0 7 3 1
(min
value of row is subtracted from each item of the row)
Upvotes: 1
Views: 502
Reputation: 887951
We can use pmin
d - do.call(pmin, d)
Or by columns
library(matrixStats)
d - colMins(as.matrix(d))[col(d)]
Upvotes: 0
Reputation: 1763
You can also use the apply
fonction with :
# 1 for the rows
apply(d, 1, function(x){x-min(x)}
# 2 for the columns
apply(d, 2, function(x){x-min(x)}
Upvotes: 1
Reputation: 3257
If I've understood your question, you could just run your 'function for columns' on the transpose of your data frame. Transposed data frames turn into matrices, so you'll need to turn it back into a data frame:
transpose <- as.data.frame(
t(yourDataFrame)
)
d2 <- transform(transpose ,A=A-(min(A)),B=B-(min(B)),C=C-(min(C)),D=D-(min(D)))
By the way this question could be clearer. I recommend you read How to create a minimal, reproducible Example: https://stackoverflow.com/help/minimal-reproducible-example
Upvotes: 1