Creating a data frame from two vectors using cbind

前端 未结 2 1531
情书的邮戳
情书的邮戳 2020-12-08 00:43

Consider the following R code.

> x = cbind(c(10, 20), c(\"[]\", \"[]\"), c(\"[[1,2]]\",\"[[1,3]]\"))
> x
     [,1] [,2] [,3]     
[1,] \"10\" \"[]\" \"         


        
2条回答
  •  庸人自扰
    2020-12-08 01:43

    Using data.frame instead of cbind should be helpful

    x <- data.frame(col1=c(10, 20), col2=c("[]", "[]"), col3=c("[[1,2]]","[[1,3]]"))
    x
      col1 col2    col3
    1   10   [] [[1,2]]
    2   20   [] [[1,3]]
    
    sapply(x, class) # looking into x to see the class of each element
         col1      col2      col3 
    "numeric"  "factor"  "factor" 
    

    As you can see elements from col1 are numeric as you wish.

    data.frame can have variables of different class: numeric, factor and character but matrix doesn't, once you put a character element into a matrix all the other will become into this class no matter what clase they were before.

提交回复
热议问题