簡體   English   中英

如何在R中組合向量

[英]how to combine vectors in R

我有一個txt格式的數據集,其中包含31968個文件,每個文件的一列中包含365個值。 我想按順序組合每個48個文件,這將帶來17520個值。

 Inputs as like
    a = (X1, x2…………………………………x48)
    b =(x49, x50 ………………………………x96)

   Expected outputs like as 
    a = (1, 2, 3, 4,………………………………..17520)
    b= (1, 2, 3, …………………………………..17520)

我如何加載31968這堆文件並在R中執行此工作。

setwd('files location')
file_names = list.files()
for(i in 1:length(file_names)){
    p = data.frame()
    for(i in i:i+47){
        setwd('input files location')
        d = read.table(file_names[i],col.names=c("id"),strip.white=TRUE)
        p = rbind(p,d)
    }
    setwd('output location')
    write.table(p,paste(file_names[i],".txt",sep=""),row.names=F)
}

請確保所有輸入文件都位於單個目錄中,並且該目錄中沒有其他文件。 將使用在48個文件的每個組合列表中讀取的第48個文件的名稱創建輸出。

由於31968/48提供666,因此創建一個包含666個向量的列表,每個向量包含48個文件名。

file_names <- list.files(path=".", pattern="\\.txt") # change the path to the directory where the files are kept
list_of_files <- lapply(1:666, function(x) file_names[((x-1)*48 + 1):((x-1)*48 + 48)])

將這些文件作為list_of_data讀入R,並使用do.call和rbind轉換為單個data.frame。

for(i in 1:666){
    list_of_data <- lapply(list_of_files[[i]], read.table, sep="\t") # put in appropriate read.table parameters for the text files
    assign(paste0("a", i), do.call(rbind, list_of_data))
    }

選擇:

for(i in 1:666){
    list_of_data <- lapply(list_of_files[[i]], read.table, sep="\t")
    assign(sprintf("a.%03d", i), do.call(rbind, list_of_data))
    }

這應該返回666個對象,例如

"a.001" "a.002" "a.003" "a.004" "a.005" "a.006" "a.007" "a.008" "a.009" "a.010" "a.011"
"a.012" "a.013" "a.014" "a.015" "a.016" "a.017" "a.018" "a.019" "a.020" "a.021" "a.022"

合並所有666個data.frame:

frames <- grep("a[.]", ls(), value=T)
library(plyr)
output <- ldply(frames, get)

暫無
暫無

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

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