如何在R中写入.txt文件? [英] how to write into .txt file in R?
问题描述
我有一个看起来像这样的数据.例如:
I have a data that looks like this.For example:
A;a
B;a
C;b
D;c
A;b
A;d
C;c
....
第一个pos =键,第二个pos =值.如果键;值,则为1,如果不是,则为0;
First pos = key , second pos = value. If key; value , then 1 ,if not then 0;
我将根据数据创建二进制矩阵.
I would to create binary matrix from data.
a b c d
A 1 1 0 1
B 1 0 0 0
C 0 1 1 0
D 0 0 0 1
我可以创建矩阵,我的代码:
I could create matrix, my code:
KeyandValue = read.table('~/RStudioProjects/TestData.txt',sep=';',header = FALSE)
tableForData <- table(KeyandValue$V1,KeyandValue$V2)
tableForData[tableForData > 1] <- 1
csvFile<- write.table(tableForData,file =
"~/RStudioProjects/TestData.csv",quote = F,sep = ";")
write.csv(csvFile)
现在,我想以这种形式重写为.txt格式:
Now, i want to re-write to .txt format in this form:
A;a;1
A;b;1
A;c;0
A;d;1
B;a;1
B;b;0
B;c;0
B;d;0
.....
我的代码:
t3<-tableForData[,]
View(t3)
然后我以这种形式查看表格
then i view table in this form
我如何以这种形式写入.txt文件?
How i can write in this form into .txt file?
推荐答案
(为了更好地与OP保持一致而进行了编辑)
(edited for better consistency with the OP)
在基本R中,您可以使用as.data.frame.table
仅在一行中完成此操作:
In base R you can do it in just one line using as.data.frame.table
:
df <- data.frame(
V1 = c("A", "B", "C", "D", "A", "A", "C"),
V2 = c("a", "a", "b", "c", "b", "d", "c"))
tableForData <- with(df, table(V1,V2))
tableForData[tableForData > 1] <- 1
t3 <- as.data.frame(tableForData) #this is the working part :)
然后 t3 是...
> head(t3)
V1 V2 Freq
1 A a 1
2 B a 1
3 C a 0
4 D a 0
5 A b 1
6 B b 0
如果行的顺序很重要,则可以对其进行排序:
You can sort it if the order of rows is important:
t3 <- t3[order(t3$V1),]
...并写入文件:
write.table(t3, "afilename.csv", sep=";", col.names=FALSE, quote=FALSE, row.names=FALSE)
这篇关于如何在R中写入.txt文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!