Reputation: 19
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
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
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