读取R中的两个冒号分隔的数据[重复]

时间:2022-05-06 03:34:39

This question already has an answer here:

这个问题在这里已有答案:

I am trying to read data separated with :: (two colons) in R. When I use sep = "::" with read.table function, I get an error message, "sep value must be one byte." I am wondering if I can read this data in R. I did not have any problem with reading this data in Python.

我试图在R中读取用::(两个冒号)分隔的数据。当我使用sep =“::”和read.table函数时,我得到一条错误消息,“sep值必须是一个字节。”我想知道我是否可以在R中读取这些数据。我在Python中读取这些数据没有任何问题。

For now, I use sep=":" and then get NA's in columns that were the other ":". So I delete columns of NA's. Is there a way to read data directly by specifying sep = "::" in R?

现在,我使用sep =“:”,然后在另一个“:”的列中获取NA。所以我删除了NA的列。有没有办法直接通过在R中指定sep =“::”来读取数据?

1 个解决方案

#1


6  

Let's say we have:

假设我们有:

A::B::C
23::34::56
12::56::87
90::43::74

in a txt file. Then we can do:

在txt文件中。然后我们可以这样做:

lines <- readLines("doublesep.txt")
> lines
[1] "A::B::C"    "23::34::56" "12::56::87" "90::43::74"

lines <- gsub("::", ",", lines)
> lines
[1] "A,B,C"    "23,34,56" "12,56,87" "90,43,74"

Now, you can either write to a file or convert to a data.frame object:

现在,您可以写入文件或转换为data.frame对象:

> read.table(text=lines, sep=",", header=T)
   A  B  C
1 23 34 56
2 12 56 87
3 90 43 74

> writeLines(lines, "doubletosingle.csv")

#1


6  

Let's say we have:

假设我们有:

A::B::C
23::34::56
12::56::87
90::43::74

in a txt file. Then we can do:

在txt文件中。然后我们可以这样做:

lines <- readLines("doublesep.txt")
> lines
[1] "A::B::C"    "23::34::56" "12::56::87" "90::43::74"

lines <- gsub("::", ",", lines)
> lines
[1] "A,B,C"    "23,34,56" "12,56,87" "90,43,74"

Now, you can either write to a file or convert to a data.frame object:

现在,您可以写入文件或转换为data.frame对象:

> read.table(text=lines, sep=",", header=T)
   A  B  C
1 23 34 56
2 12 56 87
3 90 43 74

> writeLines(lines, "doubletosingle.csv")