【问题标题】:Read a column of data in R?读取R中的一列数据?
【发布时间】:2015-12-17 10:19:35
【问题描述】:

我正在尝试仅读取 R 中的一列数据。我知道执行此操作的捷径是执行类似(假设 d1 是数据框): d1[[3]] 来读取第三列。但是,我只是好奇如果您使用 read 函数,这个简单的函数会是什么样子?你如何让它成为一个向量而不是一个截断的数据框?

【问题讨论】:

    标签: r vector dataframe statistics


    【解决方案1】:

    这是一个从 .csv 文件中仅读取一列的示例

    dat <- data.frame(a = letters[1:3], b = LETTERS[1:3], c = 1:3, d = 3:1)
    dat
      a b c d
    1 a A 1 3
    2 b B 2 2
    3 c C 3 1
    
    # write dat to a csv file
    write.csv(dat,file="mydata.csv")
    
    # scan the first row only from the file
    firstrow <- scan("mydata.csv", sep=",", what=character(0), nlines=1)
    
    # which position has the desired column (header = b in this cases)
    col.pos <- match("b", firstrow)
    
    # number of columns in data
    nc <- length(firstrow)
    
    # default of NA for desired column b; NULL for others
    colClasses <- replace(rep("NULL", nc), col.pos, NA)
    
    # read just column b
    cols.b <- read.csv("mydata.csv", colClasses = colClasses)
    cols.b
      b
    1 A
    2 B
    3 C
    

    上面读入一个数据帧。如果你想读取一个向量,

    cols.b <- read.csv("mydata.csv", colClasses = colClasses)[, 1]
    cols.b
    [1] A B C
    Levels: A B C
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多