Skip to content

Instantly share code, notes, and snippets.

@eddjberry
Created March 15, 2022 16:04
Show Gist options
  • Save eddjberry/31ca797ec780b4e7685c06dc1bd78ad2 to your computer and use it in GitHub Desktop.
Save eddjberry/31ca797ec780b4e7685c06dc1bd78ad2 to your computer and use it in GitHub Desktop.
R versus numpy when applying functions to rows and columns
# R -------------------------
x = matrix(c(1,2,0, 4,3,7), ncol = 3, byrow = T)
x
# [,1] [,2] [,3]
# [1,] 1 2 0
# [2,] 4 3 7
# row means (NB: R indexes from 1)
> apply(x, MARGIN = 1, mean)
# 1.000000 4.666667
# Python --------------------
x = np.mat('1 2 0; 4 3 7')
x
# [[1 2 0]
# [4 3 7]]
# col means
x.mean(axis=0)
# array([2.5, 2.5, 3.5])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment