Reputation:
I'm trying to print the minimum (and maximum) value for each row in a dataset. I can get it to print one row by using min(dataset1[1,])
but how can I amend this to do it for all 100 rows?
Upvotes: 0
Views: 85
Reputation: 11546
Does this work? Using dplyr package.
set.seed(123)
dat <- data.frame(c1 = round(rnorm(10,10,1)),
c2 = round(rnorm(10,10,1)),
c3 = round(rnorm(10,10,1)))
dat %>% rowwise() %>% mutate(row_min = min(c_across(c1:c3)), row_max = max(c_across(c1:c3)))
# A tibble: 10 x 5
# Rowwise:
c1 c2 c3 row_min row_max
<dbl> <dbl> <dbl> <dbl> <dbl>
1 9 11 9 9 11
2 10 10 10 10 10
3 12 10 9 9 12
4 10 10 9 9 10
5 10 9 9 9 10
6 12 12 8 8 12
7 10 10 11 10 11
8 9 8 10 8 10
9 9 11 9 9 11
10 10 10 11 10 11
Upvotes: 1
Reputation: 73782
You may use range
which gives minimum and maximum simultaneously.
t(apply(d, 2, range))
# [,1] [,2]
# X1 -0.5646982 1.3709584
# X2 -0.1061245 2.0184237
# X3 -1.3888607 2.2866454
# X4 -2.6564554 1.3201133
# X5 -1.7813084 1.8951935
# X6 -1.7631631 0.4600974
For sake of speed, try
matrixStats::colRanges(as.matrix(d))
Data:
set.seed(42)
d <- data.frame(matrix(rnorm(5*6), 5, 6))
Upvotes: 1
Reputation: 585
You can use the apply
function to run methods over each row of a data frame. For example, the following will find the minimum value of each row of the data frame dataset
:
apply(dataset, 1, min)
Upvotes: 0