将txt文件读入R中的数据帧

时间:2017-12-01 14:14:07

标签: r csv

我有一个以下格式的文本文件:

   "C1","name1","type1": 2
   "C1","name2","type4": 6
   "C2","name1","type2": 1
   "C1","name3","type1": 10

我试过了:

   db<- read.table("myfile.txt")

但是这会将文件存储为两列,并将值存储为&#34; name1&#34;,我也尝试过:

  db<- read.csv("myfile.txt", header= FALSE)

但是这会将最后两列存储为一列:

    C1   name1     type1:2
    C1   name2     type4:6
    C2   name1     type2:1
    C1   name3     type1:10

如何将最后两列存储为两个单独的列

    C1   name1     type1  2
    C1   name2     type4  6
    C2   name1     type2  1
    C1   name3     type1  10

感谢

3 个答案:

答案 0 :(得分:1)

来自separate包的tidyr可以帮助您。

   tidyr::separate(db, col = 3, into = c("type", "number"), sep = ":")

答案 1 :(得分:0)

您可以在阅读了read.csv

之后拆分列
x = read.csv("myfile.txt", header = F, sep = ",")
y = matrix(unlist(strsplit(as.character(x$V3), ":")), ncol = 2, byrow = T)

x$V3 = y[, 3]
x$V4 = y[, 4]

  V1    V2    V3  V4
1 C1 name1 type1   2
2 C1 name2 type4   6
3 C2 name1 type2   1
4 C1 name3 type1  10

答案 2 :(得分:0)

你可以这样做:

operand type mismatch for `mov'