Last active
November 5, 2024 08:17
-
-
Save alekrutkowski/0e6d6bc37d5f6810ca6f7d49ba0eb568 to your computer and use it in GitHub Desktop.
Rust extendr/rextendr code to transpose R's character matrix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use extendr_api::prelude::*; | |
#[extendr] | |
fn transpose_char_matrix(matrix: RMatrix<Rstr>) -> Robj { | |
// Take the input dimensions | |
let dims = matrix.dim(); | |
// Get the number of rows and columns | |
let nrows = dims[0] as usize; | |
let ncols = dims[1] as usize; | |
// Create a new vector to hold the transposed data | |
let mut transposed_data = Vec::with_capacity(nrows * ncols); | |
// Transpose the matrix by swapping rows and columns | |
for row in 0..nrows { | |
for col in 0..ncols { | |
// Get a reference to the element at position (row, col) | |
let value = &matrix[[row, col]]; | |
// Collect the reference for the transposed matrix | |
transposed_data.push(value); | |
} | |
} | |
// Create a Strings vector from the transposed data | |
let str_vec = Strings::from_values(transposed_data); | |
// Create the dimension vector | |
let dim = [ncols as i32, nrows as i32]; | |
// Set the dimensions attribute | |
let mut robj = str_vec.into_robj(); | |
let _ = robj.set_attrib("dim", Robj::from(&dim)); | |
// Return the transposed matrix as an R object | |
robj | |
} | |
extendr_module! { | |
mod myextendr; | |
fn transpose_char_matrix; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.