zoukankan      html  css  js  c++  java
  • 如何友好的从数据框中取出向量?


    1. a1 = c(1, 2, 3, 4, 5)
    2. a2 = c(6, 7, 8, 9, 10)
    3. a3 = c(11, 12, 13, 14, 15)
    4. aframe = data.frame(a1, a2, a3)
    5. aframe
    6. #   a1 a2 a3
    7. # 1  1  6 11
    8. # 2  2  7 12
    9. # 3  3  8 13
    10. # 4  4  9 14
    11. # 5  5 10 15
    12. avector0 <- as.vector(aframe['a2'])
    13. class(avector)
    14. # [1] "data.frame"
    问题是这样的,提问者想取出afrme中的第二列,但是尽管使用了as.vector得到的仍然是一个数据框。

    于是有人回答:
    A data frame is a list. When you subset a data frame using the name of a column and [, what you're getting is a sublist (or a sub data frame). If you want the actual atomic column, you could use [[, or somewhat confusingly (to me) you could do aframe[,2] which returns a vector, not a sublist.
    1. avector1<- aframe[['a2']]
    2. class(avector1)
    3. # [1] "numeric"

    4. avector2<- aframe[,2]
    5. class(avector2)
    6. # [1] "numeric"

    7. avector3 <- aframe[,"a2"]
    8. class(avector3)
    9. # [1] "numeric"

    10. avector4 <- aframe$a2
    11. class(avector4)
    12. # [1] "numeric"
    以上四种方式都是OK的,可是提问者还恰好用了不对的方式~ 哈哈哈

    其实主要的问题在于操作符 [ 和 [[ 
    我们可以使用
    1. ?'['
    2. ?'[['
    3. ?'[.data.frame'
    另外注意,[中有一个drop(降维)参数
    如果drop为T,则将数据框降维list....(蛋疼)
    1. > avector <-  as.vector(aframe['a2',,drop=TRUE])
    2. > class(avector)
    3. [1] "list

    1. > avector <-  as.vector(aframe['a2',drop=TRUE])
    2. Warning message:
    3. In `[.data.frame`(aframe, "a2", drop = TRUE) : 忽略'drop'参数
    4. > class(avector)
    5. [1] "data.frame"

    1. > avector <-  as.vector(aframe[,'a2',drop=F])
    2. > avector
    3.   a2
    4. 1  6
    5. 2  7
    6. 3  8
    7. 4  9
    8. 5 10
    9. > class(avector)
    10. [1] "data.frame"


    来自sf的这篇问答



     




  • 相关阅读:
    singleTon 模式
    最近的工作经验
    sql server里的快捷键
    Bridge 模式
    [转]在.NET客户端程序中使用多线程
    wse
    关于高频查询界面
    判断字段值已经存在
    获取当前供应商的联系人信息
    获取系统常量
  • 原文地址:https://www.cnblogs.com/xuanlvshu/p/5297653.html
Copyright © 2011-2022 走看看