簡體   English   中英

具有固定列數的Write.table

[英]Write.table with a fixed number of columns

我在R中創建了一個非常大的數據框,我想輸出許多子集並將其保存為csvs。 但是,我只想保留列的子集(即bin和volume)。 考慮到我正在運行一個需要使用od字段的循環,最簡單的方法是什么?

#create data frame

od    <-c("520_513", "520_513", "520_513", "520_513", "520_513", 
          "517_620", "517_620", "517_620", "517_620", "517_620")
bin   <-c(1,2,3,4,5,1,2,3,4,5)
volume<-c(1,0,4,5,6,4,4,5,6,6)

df    <-data.frame(od, bin, volume)
df1   <-split(df,df$od)

#output csvs
df1   <-for(n in names(df1))
            write.table(df1[[n]],                
                        row.names=F,
                        col.names=F, 
                        sep=",",                          
                        file=paste( n,".csv"))

這是我對517_620的輸出:

od          bin        volume
--------------------------------
517_620     1            4
517_620     2            4
517_620     3            5
517_620     4            6
517_620     5            6

但是我想要這個:

bin        volume
--------------------
    1         4
    2         4
    3         5
    4         6
    5         6

謝謝!

假設您確實想要逗號分隔的文件,而不是您說明的空格分隔,然后for循環制作幾個mod:

for(n in names(df1))    # the assignment would destroy the df1 object
            write.table(df1[[n]][ , 2:3],    # use only cols 2 and 3           
                        row.names=F,
                        col.names=F, 
                        sep=",",                          
                        file=paste0( n,".csv"))  # change to paste0 to avoid spaces

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM