Skip to content

Instantly share code, notes, and snippets.

@mkim0710
Last active October 19, 2018 16:45
Show Gist options
  • Save mkim0710/9d2470ff413cae71bee927624dc2803e to your computer and use it in GitHub Desktop.
Save mkim0710/9d2470ff413cae71bee927624dc2803e to your computer and use it in GitHub Desktop.
matrix to integer.r
set.seed(1)
m = array(runif(12) * 10, c(3, 4))
class(m)
typeof(m)
dput(m)
# > class(m)
# [1] "matrix"
# > typeof(m)
# [1] "double"
# > dput(m)
# structure(c(2.655086631421, 3.7212389963679, 5.72853363351896,
# 9.08207789994776, 2.01681931037456, 8.98389684967697, 9.44675268605351,
# 6.60797792486846, 6.2911404389888, 0.617862704675645, 2.05974574899301,
# 1.76556752528995), .Dim = 3:4)
m = as.integer(m)
class(m)
typeof(m)
dput(m)
# > class(m)
# [1] "integer"
# > typeof(m)
# [1] "integer"
# > dput(m)
# c(2L, 3L, 5L, 9L, 2L, 8L, 9L, 6L, 6L, 0L, 2L, 1L)
#@ ------
set.seed(1)
m = array(runif(12) * 10, c(3, 4))
class(m)
typeof(m)
dput(m)
# > class(m)
# [1] "matrix"
# > typeof(m)
# [1] "double"
# > dput(m)
# structure(c(2.655086631421, 3.7212389963679, 5.72853363351896,
# 9.08207789994776, 2.01681931037456, 8.98389684967697, 9.44675268605351,
# 6.60797792486846, 6.2911404389888, 0.617862704675645, 2.05974574899301,
# 1.76556752528995), .Dim = 3:4)
attributes(m)
# > attributes(m)
# $`dim`
# [1] 3 4
tmp = attributes(m)$`dim`
dput(tmp)
# > dput(tmp)
# 3:4
m = as.integer(m)
attributes(m)$`dim` = tmp
class(m)
typeof(m)
dput(m)
# > class(m)
# [1] "matrix"
# > typeof(m)
# [1] "integer"
# > dput(m)
# structure(c(2L, 3L, 5L, 9L, 2L, 8L, 9L, 6L, 6L, 0L, 2L, 1L), .Dim = 3:4)
#@ ------
set.seed(1)
m = array(runif(12) * 10, c(3, 4))
class(m)
typeof(m)
dput(m)
# > class(m)
# [1] "matrix"
# > typeof(m)
# [1] "double"
# > dput(m)
# structure(c(2.655086631421, 3.7212389963679, 5.72853363351896,
# 9.08207789994776, 2.01681931037456, 8.98389684967697, 9.44675268605351,
# 6.60797792486846, 6.2911404389888, 0.617862704675645, 2.05974574899301,
# 1.76556752528995), .Dim = 3:4)
as.integer.matrix = function(input) {
if (class(input) != "matrix") {
stop("error1")
} else {
output = as.integer(input)
attributes(output) = attributes(input)
}
output
}
m = as.integer.matrix(m)
class(m)
typeof(m)
dput(m)
# > class(m)
# [1] "matrix"
# > typeof(m)
# [1] "integer"
# > dput(m)
# structure(c(2L, 3L, 5L, 9L, 2L, 8L, 9L, 6L, 6L, 0L, 2L, 1L), .Dim = 3:4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment