将制表符分隔的字符串转换为数据框

时间:2018-11-07 15:27:26

标签: r

我有一个长字符串,看起来像这样,除了在我显示双反斜杠的地方,实际上只有一个反斜杠。

char.string <- "BAT\\tUSA\\t\\tmedium\\t0.8872\\t9\\tOff production\\tCal1|Cal2\\r\\nGNAT\\tCAN\\t\\small\\t0.3824\\t11\\tOff production\\tCal3|Cal8|Cal9\\r\\n"

我尝试了以下方法。

df <- data.frame(do.call(rbind, strsplit(char.string, "\t", fixed=TRUE)))

df <- ldply (df, data.frame)

第一个返回向量。第二个返回数千行两列,其中一个由序号组成,第二个由所有数据组成。

我正在努力实现这一目标:

item = c("BAT", "GNAT")
origin = c("USA", "CAN")
size = c("medium", "small")
lot = c("0.8872", "0.3824")
mfgr = c("9", "11")
stat = c("Off production", "Off production")
line = c("Cal1|Cal2", "Cal3|Cal8|Cal9")

df = data.frame(item, origin, size, lot, mfgr, stat, line)
df

  item origin   size    lot mfgr           stat           line
1  BAT    USA medium 0.8872    9 Off production      Cal1|Cal2
2 GNAT    CAN  small 0.3824   11 Off production Cal3|Cal8|Cal9

2 个答案:

答案 0 :(得分:1)

read.table()在这里实际上应该没问题,但是您有两个基本问题:

  1. 有两种错别字
    一种。我假设您不想要\\small,而是small
    b。您有\\t\\tmedium,我想只想\\tmedium
  2. "\\t""\t"
  3. 不同

尝试一下

# Start with your original input
char.string <- "BAT\\tUSA\\t\\tmedium\\t0.8872\\t9\\tOff production\\tCal1|Cal2\\r\\nGNAT\\tCAN\\t\\small\\t0.3824\\t11\\tOff production\\tCal3|Cal8|Cal9\\r\\n"
# Eliminate the typos
char.string <- sub("\\\\s", "s", char.string)
char.string <- sub("\\\\t\\\\t", "\\\\t", char.string)
# Convert \\t, etc. to actual tabs and newlines
char.string <- gsub("\\\\t", "\t", char.string)
char.string <- gsub("\\\\r", "\r", char.string)
char.string <- gsub("\\\\n", "\n", char.string)
# Read the data into a dataframe
df <- read.table(text = char.string, sep = "\t")
# Add the colnames
colnames(df) <- c("item", "origin", "size", "lot", "mfgr", "stat", "line")
# And take a look at the result
df



  item origin   size    lot mfgr           stat           line
1  BAT    USA medium 0.8872    9 Off production      Cal1|Cal2
2 GNAT    CAN  small 0.3824   11 Off production Cal3|Cal8|Cal9

答案 1 :(得分:0)

我对您的 char.string 中的错别字有一些自由。

library(tidyverse)

char.string <- "BAT\\tUSA\\tmedium\\t0.8872\\t9\\tOff production\\tCal1|Cal2\\r\\nGNAT\\tCAN\\tsmall\\t0.3824\\t11\\tOff production\\tCal3|Cal8|Cal9\\n"

lapply(
    str_split(gsub("\\\\n", "", char.string), "\\\\r")[[1]]
    , function(x) {
        y <- str_split(x, "\\\\t")[[1]]
        data.frame(
            item = y[1]
            , origin = y[2]
            , size = y[3]
            , lot = y[4]
            , mfgr = y[5]
            , stat = y[6]
            , line = y[7]
            , stringsAsFactors = F
        )
    }) %>%
    bind_rows()

  item origin   size    lot mfgr           stat           line
1  BAT    USA medium 0.8872    9 Off production      Cal1|Cal2
2 GNAT    CAN  small 0.3824   11 Off production Cal3|Cal8|Cal9