R - 删除数据框列中第二个空格后的所有内容

问题描述 投票:0回答:2

我在数据框中有一列,其中每个记录都是一个名称列表。

例如约翰史密斯,简史密斯,乔史密斯,朱迪史密斯等......

我想删除除整个列的名字之外的所有内容,基本上从第一个逗号开始,所以我的列只有一个名称。

EG约翰史密斯

我试过玩sub,gsub,正则表达式,但我迷路了。我刚刚开始使用R大约两天前做得很好,直到我遇到这个障碍。

任何帮助赞赏。

r dataframe
2个回答
1
投票

假设您的名字位于数据框Name中名为mydata的列中,请先尝试此操作。它说“用空字符串替换逗号后跟任何东西”。

sub(",.+", "", mydata$Name)

如果它看起来有效,请将结果分配给列:

mydata$Name <- sub(",.+", "", mydata$Name)

0
投票

如果您的数据框如下所示:

df = data.frame(names = c("John Smith, Jane Smith, Joe Smith, Judy Smith","Jane Smith, Joe Smith, Judy Smith","Joe Smith, Judy Smith","Judy Smith"))

> df
                                          names
1 John Smith, Jane Smith, Joe Smith, Judy Smith
2             Jane Smith, Joe Smith, Judy Smith
3                         Joe Smith, Judy Smith
4                                    Judy Smith

然后做:

df$first = sub(",.*","",df$names)

结果:

> df
                                          names      first
1 John Smith, Jane Smith, Joe Smith, Judy Smith John Smith
2             Jane Smith, Joe Smith, Judy Smith Jane Smith
3                         Joe Smith, Judy Smith  Joe Smith
4                                    Judy Smith Judy Smith
© www.soinside.com 2019 - 2024. All rights reserved.