[英]How to export data in text file using R in the correct format?
我在R中創建了3個數據變量,每個變量1中都有以下信息:坐標
x y
0.1 0.1
變量2:mz
100.0
100.1
100.2
100.3
....
....
999.9
變量3:強度
4.533154e-01
2.997068e-01
4.542300e-01
2.905961e-01
4.636095e-01
.....
.....
現在,我想將此信息導出為文本文件。 這樣我有以下格式
x y
0.1 0.1
100.0 2.905961e-01
100.1 4.533154e-01
100.2 2.997068e-01
100.3 4.542300e-01
....
....
999.9 2.905961e-01
我在R中為此編寫了以下代碼:
spectralData<-cbind(mz, intensity, deparse.level = 0)
foo<-c('%2.1f', '%2.8f')
cbar<-sapply(1:2,function(j) sprintf(foo[j],spectralData[,j]))
write(t(cbar),'/Desktop/cbar.txt',ncolumns=2)
data<-rbind(coordinate,spectralData,deparse.level = 0)
write.table(data, "/Desktop/test.txt", row.names = FALSE)
我收到了文本文件,但是有兩個問題。 首先,我將行號作為附加列。 我應該如何避免這種情況? 其次,mz和強度列的數字精度都會發生變化。 小數點后如何獲得相同的精度? 這是導出的數據的樣子
"x" "y"
"1" 0.100000001490116 0.100000001490116
"2" 100 -1.77635683940025e-15
"3" 100.099998474121 0.0266907754084524
"4" 100.199996948242 0.0533815508169102
"5" 100.300003051758 3.5527136788005e-15
"6" 100.400001525879 0.135286505970676
"7" 100.5 0.0286329399926419
為避免行號,請使用此-
write.table(data, "/Desktop/test.txt",row.names = FALSE)
如果您希望每一列都具有特定的精度(我相信這是問題的一部分),那么一種方法是首先通過sprintf
語句運行數據幀以創建字符串數組。 然后使用write
將數據寫入文件-引號不會直通。 這是一個例子。
fbar<-sin((1:10)/10)
fbar<-matrix(fbar,5)
#fbar
# [,1] [,2]
#[1,] 0.09983342 0.5646425
#[2,] 0.19866933 0.6442177
#[3,] 0.29552021 0.7173561
#[4,] 0.38941834 0.7833269
#[5,] 0.47942554 0.8414710
foo<-c('%2.8f', '%2.3f')
cbar<-sapply(1:2,function(j) sprintf(foo[j],fbar[,j]) )
write(t(cbar),'cbar.txt',ncolumns=2)
#cbar
#0.09983342 0.565
#0.19866933 0.644
#0.29552021 0.717
#0.38941834 0.783
#0.47942554 0.841
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.