Preserve names when coercing vector from binary to `as.numeric`?

后端 未结 2 1922
误落风尘
误落风尘 2021-02-18 22:08

In R, when you coerce a vector from binary to numeric, the names are stripped away.

There are a few possible solutions, which I\'ve outlined before. It seems dangerous t

2条回答
  •  醉话见心
    2021-02-18 22:52

    One possibility is to use the mode<- replacement function to change the internal storage mode (type) of the object. Also, integers are more appropriate than doubles (i.e. numerics) for this case of logical coercion.

    mode(example_vec) <- "integer"
    example_vec
    # Y N M P L J H O F D 
    # 0 1 0 0 1 1 1 1 1 1 
    

    From help(mode) -

    mode(x) <- "newmode" changes the mode of object x to newmode. This is only supported if there is an appropriate as.newmode function, for example "logical", "integer", "double", "complex", "raw", "character", "list", "expression", "name", "symbol" and "function". Attributes are preserved.

    The documentation also notes that storage.mode<- is a more efficient primitive version of mode<-. So the following could also be used.

    storage.mode(example_vec) <- "integer" 
    

    But as @joran pointed out in the comments, it looks like class<- also does the same thing.

提交回复
热议问题