How to find the row standard deviation of columns having same name in R data frame?

To find the row standard deviation of columns having same name in R data frame, we can follow the below steps −

• First of all, create a data frame with some columns having same name.

• Then, use tapply along with colnames and sd function to find the row standard deviation of columns having same name.

Example

Create the data frame

Let’s create a data frame as shown below −

df<-
data.frame(x=rpois(25,5),x=rpois(25,1),y=rpois(25,2),y=rpois(25,5),check.names=FALSE)
df

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

   x x y  y
1  4 0 2  9
2  8 3 3  4
3  5 1 1  7
4  3 1 1  5
5  8 1 2  5
6  3 1 1  5
7  3 1 4  5
8  3 1 0  4
9  4 2 1  3
10 7 0 4  2
11 7 1 2  4
12 7 2 2 10
13 5 2 0  1
14 5 0 1  7
15 2 1 1  6
16 7 1 1  8
17 5 0 0  7
18 8 1 1  9
19 6 1 2  9
20 3 0 3  9
21 7 0 4  5
22 7 2 5  5
23 4 0 2  5
24 2 0 4  5
25 2 0 4  4

Find the row standard deviation of columns having same name

Using tapply along with colnames and sd function to find the row standard deviation of columns having same name in data frame df −

df<-
data.frame(x=rpois(25,5),x=rpois(25,1),y=rpois(25,2),y=rpois(25,5),check.names=FALSE)
t(apply(df,1, function(x) tapply(x,colnames(df),sd)))

Output

         x          y
[1,]  2.8284271 4.9497475
[2,]  1.4142136 0.7071068
[3,]  3.5355339 2.8284271
[4,]  0.0000000 2.1213203
[5,]  2.1213203 4.9497475
[6,]  5.6568542 0.7071068
[7,]  1.4142136 0.7071068
[8,]  4.2426407 1.4142136
[9,]  1.4142136 0.7071068
[10,] 1.4142136 0.0000000
[11,] 4.2426407 2.1213203
[12,] 0.0000000 2.8284271
[13,] 6.3639610 2.8284271
[14,] 0.7071068 0.7071068
[15,] 1.4142136 1.4142136
[16,] 2.1213203 2.8284271
[17,] 4.9497475 4.2426407
[18,] 4.9497475 2.1213203
[19,] 2.1213203 1.4142136
[20,] 2.8284271 3.5355339
[21,] 2.1213203 2.8284271
[22,] 2.1213203 0.7071068
[23,] 1.4142136 3.5355339
[24,] 3.5355339 2.1213203
[25,] 3.5355339 4.9497475