Search code examples
rattributescustom-attributesnames

Changing 'names' attributes of list


Hello I am analyzing some data and trying to use a package that contains a object that has to be formatted in such a way. I have never seen this type of format and I am not sure how to generate it. When I call the object in R this is the strange object:

> a
     A      B          C            D         E          F 
0.00000000 1.34529412 0.31571429 1.26327103 0.32615385 1.12585586 

Here are some attributes of this object a:

> str(a)
 Named num [1:6] 0 1.345 0.316 1.263 0.326 ...
 - attr(*, "names")= chr [1:6] "" "A" "B" "C" ...

> class(a)
[1] "numeric"

I can write "a" to a .csv format with the standard write.csv command, and it formats it nicely with two columns, one column with the characters, and the other with the numbers. When I try to read it back in R using read.csv it returns it correctly as a data frame with two columns. However, the function that I am trying to use doesn't like the data frame format and prefers whatever format "a" is in.

So it is possible to take an example data set such as:

> L <- c("A","B","C","D","E","F")
> R <- c(0.00000000,1.34529412,0.31571429,1.26327103,0.32615385,1.12585586 )
> T <- list(L=L,R=R)
> Example <- as.data.frame(T)
> Example
  L     R
1 A 0.00000000
2 B 1.34529412
3 C 0.31571429
4 D 1.26327103
5 E 0.32615385
6 F 1.12585586 

And turn it back into this?

     A      B          C            D         E          F 
0.00000000 1.34529412 0.31571429 1.26327103 0.32615385 1.12585586 

With these attributes?

  > str(a)
     Named num [1:6] 0 1.345 0.316 1.263 0.326 ...
     - attr(*, "names")= chr [1:6] "" "A" "B" "C" ...

    > class(a)
    [1] "numeric"

Thank you for the help!


Solution

  • I think this is the sort of thing you're looking for:

    newExample <- Example$R
    names(newExample) <- Example$L