What is the best way to export an R array to a .npy file for later use in Numpy?
Toy data:
v1 <- c(1,2,3,4,5,6,7,8,9)
v2 = v1 1
v3 = v2 1
# Array to export = a
a <- array(c(v1,v2,v3), dim=c(3,3,3))
print(a)
CodePudding user response:
- We can use
reticulate
library and importnumpy
package asnp
, then we can save and load.npy
files
library(reticulate)
np <- import("numpy")
a <- np$array(a)
np$save("my_array" , a)
np$load("my_array.npy")
- Output
, , 1
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
, , 2
[,1] [,2] [,3]
[1,] 2 5 8
[2,] 3 6 9
[3,] 4 7 10
, , 3
[,1] [,2] [,3]
[1,] 3 6 9
[2,] 4 7 10
[3,] 5 8 11
CodePudding user response:
Use reticulate
package to accomplish this:
reticulate::r_to_py(a)$dump('filename.npy')
then go to python and do
import numpy as np
np.load('filename.npy', allow_pickle = True)