繁体   English   中英

比较一个csv文件和多个csv文件并写入新的csv文件R

[英]Compare one csv file to multiple csv files and write new csv files R

我对R循环很陌生,所以如果对此问题在其他地方提出过,我深表歉意。

读取所有30个CSV文件->按种类将文件A种类与其他30个CSV文件进行比较->为仅包含匹配种类的30个文件中的每个文件编写一个新的CSV文件

文件A的一列名称为190种( $name )。 其他30个csv文件中的每个都有一个带有种类( $SBSname )的列,该列中$SBSname列中的种类数不同,可以复制的范围在100-500之间(因此CSV文件可以大于190行)。 但是我不知道该怎么写...

这就是我目前所拥有的...

我已经循环了所有CSV文件:

30files = list.files(pattern="*.csv")
for (i in 1:length(30files)) assign(30files[i], read.csv(30files[i]))

我有仅将一个CSV文件( branching.csv )与文件A进行比较的代码:

> str(FileA)
'data.frame':   **190 obs. of  1 variable**:
 $ name: Factor w/ 190 levels "Acaena novae zelandiae",..: 1 2 3 4 5 6 7 8 9 10 ...

> str(branching.csv)
'data.frame':   **4055 obs. of  7 variables:**
 $ SBSname              : Factor w/ 2877 levels "Abies alba","Abies nordmanniana",..: 794 2075 1049 162 132 333 541 1840 272 1553 ...
 $ SBS.number        : int  16443 26711 40171 40398 40867 41151 37871 42412 35847 36245 ...
 $ general.method    : Factor w/ 5 levels "derivation from morphologies or other plant traits",..: 3 1 2 2 2 2 2 2 2 2 ...
 $ branching         : Factor w/ 2 levels "no","yes": 2 2 1 1 1 1 1 1 1 1 ...
 $ valid             : int  1 1 1 1 1 1 1 1 1 1 ...
 $ reference         : Factor w/ 6 levels "Barkman, J.J.(1988): New systems of plant growth forms and phenological plant types",..: 1 1 3 3 3 3 3 3 3 3 ...
 $ original.reference: Factor w/ 97 levels "Aarssen, L.W. (1981): The biology of Canadian weeds. 50. Hypochoeris radicata L.",..: 9 9 20 3 3 3 3 3 33 33 ...

Species<-branching.csv[(branching.csv$SBSname %in% FileA$name),]
write.csv(Species, file = "Branching.csv")

> str(Species)
'data.frame':   **298 obs. of  7 variables:**
 $ name              : Factor w/ 2877 levels "Abies alba","Abies nordmanniana",..: 1049 162 1548 47 57 1647 1060 2788 2094 1976 ...
 $ SBS.number        : int  40171 40398 36280 40532 41629 42495 40103 32792 32892 30583 ...
 $ general.method    : Factor w/ 5 levels "derivation from morphologies or other plant traits",..: 2 2 2 2 2 2 2 2 2 2 ...
 $ branching         : Factor w/ 2 levels "no","yes": 1 1 1 1 1 1 1 2 1 2 ...
 $ valid             : int  1 1 1 1 1 1 1 1 1 1 ...
 $ reference         : Factor w/ 6 levels "Barkman, J.J.(1988): New systems of plant growth forms and phenological plant types",..: 3 3 3 3 3 3 3 3 3 3 ...
 $ original.reference: Factor w/ 97 levels "Aarssen, L.W. (1981): The biology of Canadian weeds. 50. Hypochoeris radicata L.",..: 20 3 33 33 33 33 33 44 44 44 ...

任何帮助或建议将是巨大的。 不必一定要循环!

这个简单的循环怎么样?

library(dplyr)
for(i in 1:length(30files))
{
   csv.matching = read.csv(30files[i]) %>% inner_join(FileA, by=c("SBSname"="name"))
   write.csv(csv.matching, file=gsub("\\.csv", "_matchin.csv", 30files[i]), na="")
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM