0

i have a task that i need to complete in R studio using R language. i'm new to this. i have a "CSV" file with a table that consists of 80 columns and 568 rows after i sampled 80% of the original data file. now i need to add a column to the table and calculate the (max - min) of each row and that column will show the results of each row in this new data file.

data <- read.csv(file.choose(), header=T)
data

data$maxSubMin <- for(i in 1:568){
  max(data[i,1:78]) - min(data[i,1:78])
}

there are no errors shown in the log, but there is no new column... somebody knows whats the reason?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213

2 Answers2

1

You can use row-wise apply :

data$maxSubMin <- apply(data[,1:78], 1, function(x) max(x) - min(x))

You can also take diff of range

data$maxSubMin <- apply(data[,1:78], 1, function(x) diff(range(x)))

Using rowMaxs and rowMins from matrixStats :

library(matrixStats)
data$maxSubMin <- rowMaxs(as.matrix(data[,1:78]))- rowMins(as.matrix(data[,1:78]))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

The issue is that the for loop returns NULL. Hence you don't get a new column. To make your for loop work you have to do the assignment inside the loop, i.e.

for(i in 1:nrow(data)){
  data$maxSubMin[i] <- max(data[i,1:ncol(data)]) - min(data[i,1:ncol(data)])
}

Nonetheless the preferred approach would be to use apply as already suggested by @RonakShah. Using the iris dataset as example data:

#data <- read.csv(file.choose(), header=T)
data <- iris[,-5]

data$maxSubMin <- apply(data, 1, function(x) max(x, na.rm = TRUE) - min(x, na.rm = TRUE))
head(data)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width maxSubMin
#> 1          5.1         3.5          1.4         0.2       4.9
#> 2          4.9         3.0          1.4         0.2       4.7
#> 3          4.7         3.2          1.3         0.2       4.5
#> 4          4.6         3.1          1.5         0.2       4.4
#> 5          5.0         3.6          1.4         0.2       4.8
#> 6          5.4         3.9          1.7         0.4       5.0
stefan
  • 90,330
  • 6
  • 25
  • 51