开发者

Combine arguments of different classes

开发者 https://www.devze.com 2023-03-20 02:04 出处:网络
Let me elaborate with an example: mystr = \"foo\" intvector = c(1,2,3,4,5) trial1 = c(mystr,intvector) sapply(trial1,class)

Let me elaborate with an example:

mystr = "foo"
intvector = c(1,2,3,4,5)
trial1 = c(mystr,intvector)
sapply(trial1,class)

trial2 = mat.or.vec(1+length(intvector),1)
trial2[1] = mystr
trial2[2:length(trial2)] = intvector
sapply(trial2,class)

Both return

        foo           1           2           3           4           5 
"character" "character" "character" "character" "character" "character" 

As you can see, R converts/casts the numeric type to character type for me, which is not what I want. Thanks :)

EDIT: I will use the result to append (rbind) it directly to a data.frame, which initially will be empty, so the column classes will 开发者_如何转开发not yet be defined.


There is no way you can avoid if you do not use lists. The c function will coerce to "lowest common denominator", which in this case is "character':

 trial1 = list(mystr,intvector)
 sapply(trial1,class)
#[1] "character" "numeric"  


I believe this should work. If anyone finds a better solution, without using lists, please let me know.

trial3 = data.frame(I(mystr), t(intvector))
sapply(trial3,class)

Produces:

    mystr        X1        X2        X3        X4        X5 
   "AsIs" "numeric" "numeric" "numeric" "numeric" "numeric" 

Note that we have to wrap mystr in I and transpose the intvector in order for this to work.

0

精彩评论

暂无评论...
验证码 换一张
取 消