在 R 中将单独的 column/rows 合并为一个 column/row

Combine separate column/rows as one column/row in R

使用 txt.file,我有这个数据集:

                                   Xenopsylla cheopis    Echinolaelaps sp.      
Maxomys rajah                         1                    3                                                      
Callosciurus prevostii borneensis     4                    2    

使用此功能,

test<-read.table("data.txt",header=T)
              Xenopsylla   cheopis    Echinolaelaps   sp.      
Maxomys        rajah         1            3                                                      
Callosciurus   prevostii   borneensis     4            2  

R 似乎将我的数据识别为不同 columns/rows 并产生此错误:

Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec,  : 
  line 2 did not have 4 elements

我尝试使用 textConnection 但它似乎没有产生我想要的结果

首先,就像我在这里所做的那样,将您的数据存储在字符向量中:

test<-readChar("C:/Users/Julian/Downloads/file.txt", file.info("C:/Users/Julian/Downloads/file.txt")$size)

显然,您需要将我的文件路径替换为您的文件路径。 然后你用 gsub()

去掉 Genus 和 Species 之间的 space
test<-gsub("([[:lower:]])([[:space:]])([[:lower:]])", "\1\3",test)

最后,您可以使用带有 text 参数的 read.table() 读取您的数据:

 a<-read.table(text=test,sep="\t",header=TRUE,row.names = 1)
 a

                                Xenopsyllacheopis Echinolaelapssp. Ixodessp.
Maxomysrajah                                    3                8         9
Callosciurusprevostiiborneensis                 5                7         1
Sundamysmuelleri                                3                5         7
Niviventercremoriventer                         6                8         9

编辑: 在评论中回答 OP 的新问题:

"([[:lower:]])([[:space:]])([[:lower:]])"

使我们能够找到我们使用 readChar() 创建的与此模式匹配的字符串的所有部分。此模式是:小写字母后跟空白 space 后跟小写字母。

你可以理解这匹配属名和种名,但不匹配种名和后面的属,因为属以大写字母开头。

现在 "\1\3" 部分意味着我们保留我们的第一部分和第三部分 "([[:lower:]])([[:space:]])([[:lower:]])" 模式。即 ([[:lower:]])([[:lower:]])。因为 "\1\3" 中的 "\1\3 之间没有 space,所以我们将在没有 space 的情况下加入它们。因此我们将使用 Genusspecies 而不是 Genus species。