1

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
stuckcom
  • 19
  • 5

2 Answers2

1

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])
}
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

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))
akrun
  • 874,273
  • 37
  • 540
  • 662