用R取得逗号前的字符串 [英] Get the strings before the comma with R

查看:396
本文介绍了用R取得逗号前的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是R的初学者.现在,我在这样的data.frame中有一个向量

I am a beginner with R. Now, I have a vector in a data.frame like this

city
Kirkland,
Bethesda,
Wellington,
La Jolla,
Berkeley,
Costa, Evie KW172NJ
Miami,
Plano,
Sacramento,
Middletown,
Webster,
Houston,
Denver,
Kirkland,
Pinecrest,
Tarzana,
Boulder,
Westfield,
Fair Haven,
Royal Palm Beach, Fl
Westport,
Encino,
Oak Ridge,

我要清洁它.我要的是逗号前的所有城市名称.如何在R中得到结果?谢谢!

I want to clean it. What I want is all the city names before the comma. How can I get the result in R? Thanks!

推荐答案

您可以将gsub与regexp一起使用:

You can use gsub with a bit of regexp :

cities <- gsub("^(.*?),.*", "\\1", df$city)

这也是可行的:

cities <- gsub(",.*$", "", df$city)

这篇关于用R取得逗号前的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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