Skip to content

Instantly share code, notes, and snippets.

@alekrutkowski
Last active November 5, 2024 08:17
Show Gist options
  • Save alekrutkowski/0e6d6bc37d5f6810ca6f7d49ba0eb568 to your computer and use it in GitHub Desktop.
Save alekrutkowski/0e6d6bc37d5f6810ca6f7d49ba0eb568 to your computer and use it in GitHub Desktop.
Rust extendr/rextendr code to transpose R's character matrix
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;
}
@alekrutkowski
Copy link
Author

alekrutkowski commented Oct 29, 2024

> aaa
     [,1]      [,2]    
[1,] "efffasw" "fdxfj" 
[2,] "wqweqe"  "yjjyjy"
[3,] NA        "rweaa" 

> t(aaa)
     [,1]      [,2]     [,3]   
[1,] "efffasw" "wqweqe" NA     
[2,] "fdxfj"   "yjjyjy" "rweaa"

> transpose_char_matrix(aaa)
     [,1]      [,2]     [,3]   
[1,] "efffasw" "wqweqe" NA     
[2,] "fdxfj"   "yjjyjy" "rweaa"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment