从其他列创建特定值的新列

Create new column of specific values from other columns

我有县数据,但我想创建仅列出各州的列。基本上,我有这个:

County       
County 1, NY  
County 2, NY    
County 3, NY
County 4, TX
County 5, TX
County 6, IL
County 7, IL

但我想要这个:

County          State 
County 1, NY     NY
County 2, NY     NY
County 3, NY     NY
County 4, TX     TX
County 5, TX     TX
County 6, IL     IL
County 7, IL     IL

有没有办法让 R 'find' 和 select 在我的 County 列中包含“NY”、“TX”等并从中创建一个 State 列?谢谢!

dat$State <- gsub(".*\b([^[:space:]]+)[[:space:]]*$", "\1", dat$County)
dat
#         County State
# 1 County 1, NY    NY
# 2 County 2, NY    NY
# 3 County 3, NY    NY
# 4 County 4, TX    TX
# 5 County 5, TX    TX
# 6 County 6, IL    IL
# 7 County 7, IL    IL

Walk-through:

  • .* 是零个或多个东西,在这里我们可以丢弃它
  • \b 是一个 word-boundary,以确保我们得到所有的状态,而不仅仅是它的第二个字母
  • (...)是我们后面会回忆的一组;第一个字符串中括号中的任何内容都可以在第二个字符串中通过其位置引用,如 \1
  • [^[:space:]]+ 是一个 character-class,[:space:] 表示任何 space-like 的东西,而 [^...] 否定它,所以这意味着任何 non-blank-space;尾随 + 表示 one-or-more
  • [[:space:]]* 和以前一样是 not-negated blank-space 字符 class,但现在 * 表示 zero-or-more
  • $ 是 end-of-string

数据

dat <- structure(list(County = c("County 1, NY", "County 2, NY", "County 3, NY", "County 4, TX", "County 5, TX", "County 6, IL", "County 7, IL")), row.names = c(NA, -7L), class = "data.frame")

如果所有行的数据都与显示的完全一致,您可以删除所有内容,直到最后一个逗号和空格后跟它。

df$County <- sub('.*,\s', '', df$County)

如果州名称可以出现在数据中的任何位置,我们可以使用内置常量 state.abb 并使用它创建一个模式来提取数据(如果出现在 county 列中的任何位置)。

library(stringr)
df$State <- str_extract(df$County, str_c(state.abb, collapse = '|'))

我们可以使用str_remove

library(stringr)
df$State <- str_remove(df$County, ".*,\s+")