我有一个字符向量,其中单个元素包含由逗号分隔的多个字符串。我从一个数据框架中提取了这个列表,它看起来如下所示:
[1] "Acworth, Crescent Lake, East Acworth, Lynn, South Acworth"
[2] "Ferncroft, Passaconaway, Paugus Mill"
[3] "Alexandria, South Alexandria"
[4] "Allenstown, Blodgett, Kenison Corner, Suncook (part)"
[5] "Alstead, Alstead Center, East Alstead, Forristalls Corner, Mill Hollow"
[6] "Alton, Alton Bay, Brookhurst, East Alton, Loon Cove, Mount Major, South Alton, Spring Haven, Stockbridge Corners, West Alton, Woodlands"
[7] "Amherst, Baboosic Lake, Cricket Corner, Ponemah"
[8] "Andover, Cilleyville, East Andover, Halcyon Station, Potter Place, West Andover"
[9] "Antrim, Antrim Center, Clinton Village, Loverens Mill, North Branch"
[10] "Ashland" 我想获得一个新的字符向量,其中每个字符串都是这个字符向量中的一个元素,即:
[1] "Acworth", "Crescent Lake", "East Acworth", "Lynn", "South Acworth"
[6] "Ferncroft", "Passaconaway", "Paugus Mill", "Alexandria", "South Alexandria"我使用了strsplit()函数,但是这会返回一个列表。当我试图把它变成一个字符向量时,它会恢复到原来的状态。
我相信这是一个非常简单的问题--任何帮助都是非常感谢的!谢谢!
发布于 2016-01-21 15:32:44
你的帖子标题暗示你想要唯一的字符串,所以
unique(unlist(strsplit(myvec, split=",")))或
unique(unlist(strsplit(myvec, split=", ")))如果你总是在逗号后面有一个空格。
发布于 2016-01-21 15:33:30
您可以去掉空格,用"\\s*,\\s*"正则表达式拆分字符向量,然后unlist结果:
v <- c("Acworth, Crescent Lake, East Acworth, Lynn, South Acworth", "Ferncroft, Passaconaway, Paugus Mill", "Alexandria, South Alexandria", "Allenstown, Blodgett, Kenison Corner, Suncook (part)", "Alstead, Alstead Center, East Alstead, Forristalls Corner, Mill Hollow", "Alton, Alton Bay, Brookhurst, East Alton, Loon Cove, Mount Major, South Alton, Spring Haven, Stockbridge Corners, West Alton, Woodlands", "Amherst, Baboosic Lake, Cricket Corner, Ponemah", "Andover, Cilleyville, East Andover, Halcyon Station, Potter Place, West Andover", "Antrim, Antrim Center, Clinton Village, Loverens Mill, North Branch", "Ashland" )
s <- unlist(strsplit(v, "\\s*,\\s*"))正则表达式匹配,两侧的零或多个空白符号(,),从而对值进行修整。即使在初始字符向量中的逗号前面有一个“野生”空格,这也会处理情况。
发布于 2016-01-22 03:55:27
作为一种替代,您还可以使用scan,如下所示:
unique(scan(what = "", text = v, sep = ",", strip.white = TRUE))strip.white = TRUE部件负责您可能拥有的任何前导或尾随空格。
注:"v“来自另一个答案。
https://stackoverflow.com/questions/34927662
复制相似问题