代码之家  ›  专栏  ›  技术社区  ›  user3245256

READR强制列类型

  •  1
  • user3245256  · 技术社区  · 7 年前

    我试图读取一个csv文件-并试图强制列是某种类型。但最后一列给了我一个错误:“Is.List.(COLYTYPE类型):未知的快捷方式:G”

    有什么建议吗?谢谢您!

    # Create data frame & write it out:
    temp <- data.frame(a = 1:1001,
                       mystring_b = c(rep(NA, 1000), "1"),
                       mystring_c = c(rep(NA, 1000), "2"))
    write.csv(temp, "temp.csv", row.names = F)
    # Grab its names:
    temp_labels <- names(read_csv("temp.csv", n_max = 0))
    # Specify data type - for each column:
    labels_type <- ifelse(grepl("mystring", temp_labels), "numeric", "guess")
    # Reading in while forcing column types:
    temp <- read_csv("temp.csv", col_types = labels_type)
    # Error in is.list(col_types) : Unknown shortcut: g
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Gregor Thomas    7 年前

    以下是对 col_types 从帮助页 ?read_csv :

    柯尔型

    … 或者,可以使用紧凑的字符串表示形式,其中每个字符表示一列: c =字符, i =整数, n =数, d =双, l =逻辑, D =日期 T =日期时间, t =时间, ? =猜测,或 _ / - 跳过列。

    所以,正如错误信息所说, "g" 不是可接受的快捷方式。你应该用 "?" 相反。

    同时,同时 read_csv 似乎很幸运从你的 "numeric" 规格,为了安全,您可能应该使用 "n" 匹配文档。实际上,如果您查看这些示例,目的是使用单个字符串,而不是长度为1的字符串向量作为规范。同样,如果你的方法在其他方面工作,你是幸运的,但最好是匹配文档,像这样:

    labels_type <- paste(ifelse(grepl("mystring", temp_labels), "n", "g"), collapse = "")