Matlab Cell Array Import via R fails -
i facing following problem. try import cell of strings readmat function in r.
matlab code:
names = {'a', 'b', 'c', 'd'}; save('rdatain.mat', 'names');
now want use set of strings in r. run following r script
r code:
library('r.matlab') names <- readmat("rdatain.mat")
readmat can apparently not handle cell type .mat data, creates strange list. solution problem? thanks.
yeah.... it's pretty weird that. wouldn't "fails", it's in format requires work. when save above cell array , load r:
> library("r.matlab") > names <- readmat("rdatain.mat") > names $names $names[[1]] $names[[1]][[1]] [,1] [1,] "a" $names[[2]] $names[[2]][[1]] [,1] [1,] "b" $names[[3]] $names[[3]][[1]] [,1] [1,] "c" $names[[4]] $names[[4]][[1]] [,1] [1,] "d" attr(,"header") attr(,"header")$description [1] "matlab 5.0 mat-file, platform: maci64, created on: sat mar 28 13:12:31 2015 " attr(,"header")$version [1] "5" attr(,"header")$endian [1] "little"
as can see, names
contains nested list each string stored in 1 x 1 matrix. can access element of list, within list, go through of elements , extract out first element of each nested element. contains each "name" or string you're looking for. can use standard sapply
call , each element in list, apply custom function extract out first element of each nested element you.
x <- sapply(names[[1]], function(n) n[[1]])
x
vector of names, , get:
> x [1] "a" "b" "c" "d"
you can access each "name" standard vector indexing:
> x[1] [1] "a" > x[2] [1] "b" > x[3] [1] "c" > x[4] [1] "d"
Comments
Post a Comment