Wednesday, February 4, 2015

R7. Adding Mean Column and Row to a data.frame in R

The rowMeans and colMeans functions are used.


If we did not explicitly change the row.names argument in the data.frame construct, the row numbers would start with 1. This is contrast to languages such as Python, and other languages, which start at zero index.


Whenever we have new row or column indices in an assignment, a new row or column is created.

# ex7.R
x1 <- sample(0:9)
x2 <- sample(0:9)
x3 <- sample(0:9)
df <- data.frame(x1,x2,x3,row.names = c(0:9))
print('data.frame df =')
print(df)
print('First Column =')
print(df['x1'])
print('First Row =')
print(df[1,])
print('First Column, First Row = ')
print(df[1,'x1'])
print('Adding ave column')
df['ave'] <- rowMeans(df)
print('df =')
print(df)
print('Adding ave row')
df["ave_row",] <- colMeans(df)
print('df =')
print(df)
# [1] "data.frame df ="
# x1 x2 x3
# 0  2  3  4
# 1  7  8  2
# 2  1  4  5
# 3  0  1  7
# 4  9  0  1
# 5  8  6  8
# 6  3  5  6
# 7  4  7  0
# 8  6  9  3
# 9  5  2  9
# [1] "First Column ="
# x1
# 0  2
# 1  7
# 2  1
# 3  0
# 4  9
# 5  8
# 6  3
# 7  4
# 8  6
# 9  5
# [1] "First Row ="
# x1 x2 x3
# 0  2  3  4
# [1] "First Column, First Row = "
# [1] 2
# [1] "Adding ave column"
# [1] "df ="
# x1 x2 x3      ave
# 0  2  3  4 3.000000
# 1  7  8  2 5.666667
# 2  1  4  5 3.333333
# 3  0  1  7 2.666667
# 4  9  0  1 3.333333
# 5  8  6  8 7.333333
# 6  3  5  6 4.666667
# 7  4  7  0 3.666667
# 8  6  9  3 6.000000
# 9  5  2  9 5.333333
# [1] "Adding ave row"
# [1] "df ="
# x1  x2  x3      ave
# 0       2.0 3.0 4.0 3.000000
# 1       7.0 8.0 2.0 5.666667
# 2       1.0 4.0 5.0 3.333333
# 3       0.0 1.0 7.0 2.666667
# 4       9.0 0.0 1.0 3.333333
# 5       8.0 6.0 8.0 7.333333
# 6       3.0 5.0 6.0 4.666667
# 7       4.0 7.0 0.0 3.666667
# 8       6.0 9.0 3.0 6.000000
# 9       5.0 2.0 9.0 5.333333
# ave_row 4.5 4.5 4.5 4.500000

No comments:

Post a Comment