0
votes

I'm new to tidyverse and I'm trying to read in a Matlab .mat data structure and convert it to a tidyverse data frame but get an error setting the column headers.

data = readMat('myfile.mat')
data_tb = as_tibble(data$data, .name_repair = c(data$labels))

the readMat() call works fine but the as_tibble() generates this error:

Error in vec_as_names(name, repair = .name_repair, quiet = quiet || !is_character(.name_repair)) : 
  CHAR() can only be applied to a 'CHARSXP', not a 'character'

Note that class(data$labels) returns [1] "matrix" "array" (ditto for data$data)

I've tried hard-wiring labels e.g.

as_tibble(data$data, .name_repair = c("a", "b", "C", "D")) 

but I get the same error.

I can change the column headers individually by reading it into a tibble without specifiying .name_repair and calling

data_tb = data_tb %>% rename(new_col_name = old_col_name)

but that's messy and I would really rather work out why the .name_repair call is failing.

2

2 Answers

1
votes

Try:

as.tibble(matrix(unlist(data$data), ncol=4, byrow=T)) 

You can then set the colnames

1
votes

I managed to reproduce your error and I solved it this way:

setNames(as_tibble(data$data), data$labels)

You cannot assign a vector of new names to that argument. The .name_repair argument can take only one of these strings as input:

c("check_unique", "unique", "universal", "minimal")

Each of them tells as_tibble [and behind that to vec_as_names] to perform a certain action. Check out ?as_tibble for more infos.


Reproducible example:

library(tibble)

path <- system.file("mat-files", package = "R.matlab")
pathname <- file.path(path, "ABC.mat")
data <- R.matlab::readMat(pathname)

as_tibble(data$A, .name_repair = letters[1:3])
# Error in vec_as_names(name, repair = .name_repair, quiet = quiet || !is_character(.name_repair)) : 
#   CHAR() can only be applied to a 'CHARSXP', not a 'character'

setNames(as_tibble(data$A), data$B)
# # A tibble: 9 x 3
#     `1`   `2`   `3`
#   <int> <int> <int>
# 1     1    10    19
# 2     2    11    20
# 3     3    12    21
# 4     4    13    22
# 5     5    14    23
# 6     6    15    24
# 7     7    16    25
# 8     8    17    26
# 9     9    18    27