R数据框列仅在带下划线的逗号之前首先替换space

R dataframe column replace only first space before a comma with underscore

措辞相似的问题,但不是我要找的,有点卡住了。我有一列 "City, State " 值。有些城市有 2 个词,例如 "Grand Rapids, MI"。我想替换第一个 space,使其变为 Grand_Rapids,MI。我正在使用 separate 来创建城市和州值,因此我想在城市和州之间保留 space。我该怎么做?

Col1
Fort Myers, FL
Grand Rapids, MI

变成

Col1
Fort_Myers, FL
Grand_Rapids, MI

这样我就可以使用

df1 <- df%>%separate(Col1,c("City","State"))

得到

City         State
Fort_Myers     FL
Grand_Rapids   MI

我们可以在这里使用 sep 或者它可以匹配其他分隔符,即 'Fort' 和 'Myers' 之间的 space (或者如果它是 _)

library(dplyr)
library(tidyr)
df %>%
    separate(Col1,c("City","State"), sep=",\s*")