What should I do for calculating the mean of different columns and result shows in seperate columns
There are several ways to do this. Here is a method using functions from base R. I did one case where you get the means of every column in the data frame and another method where you select the desired columns. The mean() function is intended to work on a single vector, not multiple columns of a data frame.
set.seed(123) # for reproducibility
DF <- data.frame(A = runif(10), B = runif(10), C = runif(10))
DF
#> A B C
#> 1 0.2875775 0.95683335 0.8895393
#> 2 0.7883051 0.45333416 0.6928034
#> 3 0.4089769 0.67757064 0.6405068
#> 4 0.8830174 0.57263340 0.9942698
#> 5 0.9404673 0.10292468 0.6557058
#> 6 0.0455565 0.89982497 0.7085305
#> 7 0.5281055 0.24608773 0.5440660
#> 8 0.8924190 0.04205953 0.5941420
#> 9 0.5514350 0.32792072 0.2891597
#> 10 0.4566147 0.95450365 0.1471136
MEANS <- colMeans(DF)
MEANS
#> A B C
#> 0.5782475 0.5233693 0.6155837
#If there are columns you want to ignore
DF2 <- data.frame(Name = LETTERS[1:10], A = runif(10), B = runif(10), C = runif(10), City = LETTERS[11:20])
DF2
#> Name A B C City
#> 1 A 0.96302423 0.1428000 0.04583117 K
#> 2 B 0.90229905 0.4145463 0.44220007 L
#> 3 C 0.69070528 0.4137243 0.79892485 M
#> 4 D 0.79546742 0.3688455 0.12189926 N
#> 5 E 0.02461368 0.1524447 0.56094798 O
#> 6 F 0.47779597 0.1388061 0.20653139 P
#> 7 G 0.75845954 0.2330341 0.12753165 Q
#> 8 H 0.21640794 0.4659625 0.75330786 R
#> 9 I 0.31818101 0.2659726 0.89504536 S
#> 10 J 0.23162579 0.8578277 0.37446278 T
MEANS2 <- colMeans(DF[, c("A","B", "C")])
MEANS2
#> A B C
#> 0.5782475 0.5233693 0.6155837
Created on 2022-03-26 by the reprex package (v0.2.1)
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.
If you have a query related to it or one of the replies, start a new topic and refer back with a link.