Normalize in R Programming Iris Dataset 'x' must be an array of at least two dimensions

228 views Asked by At

I have the data iris and I want to make the data iris - mean of each column in data iris so i have code like this

y=iris[,1:4]
t=y-colMeans(y)
t

so the column show the matrix data iris - means of column. So I want to ask about how to create like that but with looping I write like this

for(i in 1:4){y[,i]=iris[,i]-colMeans(iris[,i])}

but the result problem that 'x' must be an array of at least two dimensions

Please help me fix this

2

There are 2 answers

0
akrun On

With dplyr we can do

library(dplyr)
iris <- iris %>%
             mutate(across(1:4, ~ . - mean(.)))

Or using lapply

iris[1:4] <- lapply(iris[1:4], function(x) x - mean(x))
0
Ronak Shah On

When you subset a dataframe with one column it turns that into vector. To avoid that use drop = FALSE.

for(i in 1:4){
  y[, i] = iris[,i] - colMeans(iris[,i, drop = FALSE])
}

However, as you are taking only one column at a time you can use mean instead of colMeans which is for multiple columns.

for(i in 1:4){
  y[, i] = iris[,i] - mean(iris[,i])
}