[英]R - Converting a string variable with “\t” and “\n” into a data frame
I have a varible containing string:我有一个包含字符串的变量:
"A\tB\n\C\tD"
How can I convert it into a data frame like this?我怎样才能将它转换成这样的数据框?
---------
| A | B |
---------
| C | D |
---------
I have used this workaround: first write it as.txt file and then read as.tsv file.我使用了这种解决方法:首先将其写入 as.txt 文件,然后读取 as.tsv 文件。
writeLines("A\tB\n\C\tD", "A.txt")
B <- read.table("A.txt", header = FALSE, sep = "\t")
I am pretty sure that there is a more effective way to convert one to another without creating a new file, but I cannot find it.我很确定有一种更有效的方法可以在不创建新文件的情况下将一个文件转换为另一个文件,但我找不到它。
You're right about using read.table()
.你是对的使用
read.table()
。
read.table(text=your_string, sep="\t")
, emphasis on the text
parameter.read.table(text=your_string, sep="\t")
,强调text
参数。text
parameter allows you to input a string instead of a filename. text
参数允许您输入字符串而不是文件名。 Also, in your variable string, you have "A\tB\n\C\tD"
where there is a \
before the C
, I don't know if that's an error or not but if you take that \
out, the input should be fine (like "A\tB\nC\tD"
)此外,在您的变量字符串中,您有
"A\tB\n\C\tD"
,其中在C
之前有一个\
,我不知道这是否是一个错误,但如果你把那个\
拿出来,输入应该没问题(如"A\tB\nC\tD"
)
Use the text=
argument:使用
text=
参数:
s <- "A\tB\nC\tD"
read.table(text = s, as.is = TRUE)
## V1 V2
## 1 A B
## 2 C D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.