Baltazár Tivadar Baltazár Tivadar - 2 months ago 6
R Question

How to use loop for column vectors in dataframe?

I have a dataframe like this:

example <- data.frame(tree=c(25,24,6,57,47), weed=c(4,66,88,9,6), plant=c(47,5,6,9,6), shrub=c(23,7,8,9,3))


I want the same result, which gave the following functions:

colMeans(example)
boxplot(example)


but it is important to me using loop. I have tried these:

for(i in 1:length(colnames(example))){
print(mean(i))
}

par(mfrow=c(2,2))
for(i in 1:length(colnames(example))){
print(boxplot(i))
}


Can somebody help me?

rar rar
Answer

Are you looking for something like this?

for(i in 1:ncol(example)){
     print(mean(example[,i]))
 }