简体   繁体   English

从R中的数据框中提取特定行

[英]Extracting specific rows from the data frame in R

I have the following like data in a tab-delimted text file named original 我在名为原始的制表符分隔文本文件中具有以下类似数据

Name     Symbol       Value
abcd       A            56   
de45       C            67
ji98       H            90
k9ug       K            43
phzt       L            98
prex       P            21
kadf       T            32

Also I have list of selected Symbols stored in another tab delimited text file named duplicate 另外,我在另一个制表符分隔的文本文件中存储了选定符号的列表,这些文件名为重复

Symbol     Description
 K            Intel
 P            Diary
 C            Cape
 S            Sheath
 A            Aim

I want to extract the rows from original file which has same Symbol with duplicate . 我想从原始文件中提取具有相同重复符号的行。 I want my output like the following: 我希望我的输出如下所示:

Name     Symbol       Value
abcd       A            56   
de45       C            67
k9ug       K            43
prex       P            21

I tried using the following code but some how I could not get any results or only the row of A . 我尝试使用以下代码,但有些方法却无法获得任何结果或仅获得A的行。 Here is the code which I have used 这是我使用的代码

result <- original[original$Symbol %in% duplicate$Symbol,]

Could anyone please help me. 谁能帮我。

This can be done with a simple merge : 这可以通过简单的merge来完成:

merge(original, duplicate, by.x="Symbol", by.y="symbol")
#   Symbol Name Value Description
# 1      A abcd    56         Aim
# 2      C de45    67        Cape
# 3      K k9ug    43       Intel
# 4      P prex    21       Diary

You can manually drop the Description column before or after merging if it is not relevant. 如果不相关,则可以在合并之前或之后手动删除“ Description列。

Also, I don't know if this is a problem with the question as posted or if it is a problem with your code, but: 另外,我不知道这是否与发布的问题有关,还是与您的代码有关,但是:

original[original$Symbol %in% duplicate$symbol, ]
#   Name Symbol Value
# 1 abcd      A    56
# 2 de45      C    67
# 4 k9ug      K    43
# 6 prex      P    21

Of course, you have to spell original correctly, which you did not! 当然,您必须正确拼写original ,而您却没有!

Assumptions 假设条件

  1. The correct capitalization of the word "symbol" in names(original) shows up with an upper-case S ( Symbol ). names(original)中单词“ symbol”的正确大写字母以大写S( Symbol )显示。
  2. The correct capitalization of the word "symbol" in names(duplicate) shows up with a lower-case s ( symbol ). names(duplicate)中单词“ symbol”的正确大小写以小写的s( symbol )显示。

If both are capitalized, then you can use either of the following solutions: 如果两者均大写,则可以使用以下解决方案之一:

merge(original, duplicate)
original[original$Symbol %in% duplicate$Symbol, ]

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

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