删除缺少值的数据框列中的字符串之后的所有内容 [英] Remove everything after a string in a data frame column with missing values

查看:49
本文介绍了删除缺少值的数据框列中的字符串之后的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于以下摘录的数据框:

I have a data frame resembling the extract below:

Observation Identifier   Value
Obs001      ABC_2001     54
Obs002      ABC_2002     -2
Obs003                   1
Obs004                   1 
Obs005      Def_2001/05  

我想将此数据帧转换为一个数据帧,其中将删除"_" 符号后面的字符串部分:如下所示:

I would like to transform this data frame into a data frame where portions of the string after the "_" sign would be removed: as illustrated below:

Observation Identifier_NoTime   Value
Obs001      ABC                 54
Obs002      ABC                 -2
Obs003                          1
Obs004                          1 
Obs005      Def  

我尝试过如此处讨论的strsplitgsubsub进行实验,但是不能强迫这些表述发挥作用.我必须考虑以下事实:

I tried experimenting with strsplit, gsub and sub as discussed here but cannot force those commends to work. I have to account for the fact that:

  1. 列中缺少值,我想将它们保留在原处
  2. 字符串"_"位于变量的不同位置
  3. 我还想保留其余数据框的样子

推荐答案

您可以尝试使用以下sub命令从_符号中删除所有非空格字符.

You could try the below sub command to remove all the non-space characters from _ symbol.

sub("_\\S*", "", string)

说明:

  • _匹配文字_符号.
  • \S*匹配零个或多个非空格字符.
  • _ Matches a literal _ symbol.
  • \S* Matches zero or more non-space characters.

OR

这将从_符号中删除所有字符,

This would remove all the characters from _ symbol,

sub("_.*", "", string)

说明:

  • _匹配文字_符号.
  • .*匹配任何字符零次或多次.
  • _ Matches a literal _ symbol.
  • .* Matches any character zero or more times.

这篇关于删除缺少值的数据框列中的字符串之后的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆