![](/img/trans.png)
[英]R: Reading specific columns from txt files with slightly different column headers (differing spaces) and binding them?
[英]R - cut a specific column from multiple files and bind them alltogether
我有多個文件(30個,以制表符分隔),看起來像下面的文件:
|target_id | length| eff_length| est_counts| tpm| |:------------|------:|----------:|----------:|--------:| |LmjF.27.1250 | 966| 823.427| 2932| 94.7314| |LmjF.09.0430 | 1410| 1267.430| 3603| 75.6304| |LmjF.13.0210 | 2001| 1858.430| 4435| 63.4897| |LmjF.28.0530 | 4083| 3940.430| 7032| 47.4778| |LmjF.16.1400 | 591| 448.577| 1163| 68.9761| |LmjF.29.2570 | 1506| 1363.430| 11135| 217.2770|
我正在嘗試使用以下命令從所有30個文件中切掉第五列:
fifth_colum_file1 = file1.csv[ , 5]
但是我想使過程更加自動化。
我要使用的文件具有所有模式“ bs_abundance”,因此,我認為一個不錯的出發點是使用以下命令加載要使用的所有文件:
temp = list.files(pattern="*bs_abundance")
或者也許我也可以將要使用的所有表直接直接加載到工作空間中:
for(i in temp) { x <- read.table(i, header=TRUE, comment.char = "A", sep="\\t") assign(i,x)
}
然后,如前所述,我想剪切每個文件的第五列,以便以后將它們全部綁定到具有相同行數的另一個表。
將文件放入文件夾。 對於本示例,我們將其稱為temp
。 適當設置工作目錄,或為以下示例指定完整路徑。
cols <- as.character()
files <- dir("temp")
for(i in files){
# You didn't mention a file type, but let's say it's csv
tmp <- read.csv(files[i], header = T)
tmp <- tmp[, 5]
cols <- cbind(cols, tmp)
}
然后,您可以將cols
的列與最終數據對象cbind
在一起。
這是使用lapply
的方法,該方法假定文件夾中的每個文件具有相同的行數。
# get file names
files <- dir("temp")
# remove one file
files <- files[-which(files == "removeFileName")]
# get list of vectors from 29 files
myList <- lapply(files, function(i) {temp <- read.csv(i); temp[, 5]})
# get new data.frame
dfDone <- do.call(data.frame, myList)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.