Only read selected columns

前端 未结 4 1671
春和景丽
春和景丽 2020-11-22 04:23

Can anyone please tell me how to read only the first 6 months (7 columns) for each year of the data below, for example by using read.table()?

Ye         


        
4条回答
  •  遇见更好的自我
    2020-11-22 04:57

    You do it like this:

    df = read.table("file.txt", nrows=1, header=TRUE, sep="\t", stringsAsFactors=FALSE)
    colClasses = as.list(apply(df, 2, class))
    needCols = c("Year", "Jan", "Feb", "Mar", "Apr", "May", "Jun")
    colClasses[!names(colClasses) %in% needCols] = list(NULL)
    df = read.table("file.txt", header=TRUE, colClasses=colClasses, sep="\t", stringsAsFactors=FALSE)
    

提交回复
热议问题