stuckcom
stuckcom

Reputation: 19

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

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

Upvotes: 1

Views: 278

Answers (2)

akrun
akrun

Reputation: 887148

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))

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388982

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])
}

Upvotes: 1

Related Questions