从列中查找字符串中的完全匹配项

时间:2017-02-23 15:02:36

标签: r string

我的数据集在其简短版本中如下所示:

> df
V1          V2
MID_R       1.243879014
MID         2.238147196
MID_Rcon    0.586581997
MID_U       0.833624164
MID         -0.681462038
MID         -0.593624936
MID_con     0.060862707
MID_con     -0.764524044
MID_R       -0.128464132

我编写了一个代码,只选择 MID 行并计算出它们的方法:

MID_match <- c("MID^") # choosing specific pattern to search through conditions
MID <- df[grepl(paste(MID_match, collapse="|"), df$V1), ] # grouping across this pattern
MID$V2 <- as.numeric(as.character(MID$V2)) 
mean_MID <- mean(MID$V2) # calculating mean
MID_mean = rbind(MID_mean, data.frame(mean_MID))

我瞄准的第一行和第二行的输出应该如下所示:

> MID_match
  [1] "MID"

> MID
    V1          V2
MID         2.238147196
MID         -0.681462038
MID         -0.593624936

但是,我得到了构成字符串 MID 的所有行,例如,初始数据集:

> MID

V1          V2
MID_R       1.243879014
MID         2.238147196
MID_Rcon    0.586581997
MID_U       0.833624164
MID         -0.681462038
MID         -0.593624936
MID_con     0.060862707
MID_con     -0.764524044
MID_R       -0.128464132

我尝试使用grep函数,但它没有工作:

MID_match <- df$V1(grep("\\bMID\\b", df$V1))

有关如何删除确切 MID 值的任何想法?

2 个答案:

答案 0 :(得分:1)

我认为我不能很好地抓住你的问题,但如果你的目标只是选择<UserControl x:Class="WpfSinergoHMIControls.RoundedButton" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:WpfSinergoHMIControls" mc:Ignorable="d"> <UserControl.Template> <ControlTemplate TargetType="UserControl"> <Button Content="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" Click="button_Click" PreviewMouseDown="Button_MouseDown" PreviewMouseUp="Button_MouseUp"> <Button.Resources> </Button.Resources> <Button.Template> <ControlTemplate TargetType="Button"> <Border Width="{Binding Size}" Height="{Binding Size}" BorderBrush="#FF3C7FB1" BorderThickness="1" CornerRadius="5" Name="RoundedButtonBorder"> <Border.Background> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#3a4451" Offset="0"/> <GradientStop Color="#0b2039" Offset="1"/> </LinearGradientBrush> </Border.Background> <ContentPresenter VerticalAlignment="{TemplateBinding VerticalAlignment}" HorizontalAlignment="{TemplateBinding HorizontalAlignment}"/> </Border> </ControlTemplate> </Button.Template> </Button> </ControlTemplate> </UserControl.Template> 行,那么你可以用这个完成:

<local:RoundedButton HorizontalAlignment="Center" VerticalAlignment="Center" Height="73" Margin="35,10,282,236" FontSize="30"  Width="200" Content="Hello" Foreground="Red"/>

答案 1 :(得分:1)

请勿在此处使用字符串搜索,请使用比较:

df[df$V1 == 'MID', ]

这将更有效率,而且代码更少。