Add Min Row to R

I read a lot of similar questions, but can't get the code to work. I just want to add a row to the bottom of my data frame (df), which has a minimum value for each column for columns 2: 8. Below is my code (which works) to add a common row, but I need a minimal row.

df[(nrow(df)+ 1),(2:8)] <- colSums(df[,2:8], na.rm=TRUE) 

I tried to get colMins in the matrixStats package to work, but cannot for some reason. Any help would be appreciated!

+5
source share
2 answers

We can try colMins from library(matrixStats)

 library(matrixStats) rbind(df, c(NA,colMins(as.matrix(df[2:8])))) 

Update

To replace NA with "MIN",

 rbind(df, c('MIN',as.list(colMins(as.matrix(df[2:8]))))) 

Or another approach is to convert to matrix and use addmargins

 addmargins(`row.names<-`(as.matrix(df[-1]), df$ID), 1, FUN=min) 

data

 set.seed(24) df <- cbind(ID= 1:10,as.data.frame(matrix(sample(1:9, 7*10, replace=TRUE), ncol=7))) 
+4
source

In the R base, you can use sapply() to create an atomic vector of minimal columns, and then rbind() to attach it to the original data. I added NA for the first value, since we need something there to add it to the source data.

 rbind(df, c(NA, sapply(df[2:8], min, na.rm = TRUE))) 

Obviously, this assumes only 8 columns, and therefore df[-1] can be used instead of df[2:8] .

And to increase speed, we can use vapply() over sapply() , because we know that the result will be a single numerical value.

 rbind(df, c(NA, vapply(df[-1], min, 1, na.rm = TRUE))) 

Update: In response to your comment on another answer - to get "MIN" in the first column and the minimum values โ€‹โ€‹in all the rest, we can configure the call to the named list and do it all at once. Thus, we do not mix column classes (character and number) and end with unexpected classes in the columns of the resulting data.

 rbind( df, c(setNames(list("MIN"), names(df)[1]), lapply(df[-1], min, na.rm = TRUE)) ) 
+5
source

Source: https://habr.com/ru/post/1237219/


All Articles