子集矢量字符串的名称(基于案例)

时间:2012-01-03 19:13:34

标签: r

我想拆分一个名字的矢量:

names <- c("DOE John", "VAN DYKE Dick", "SMITH Mary Jane") 

分为两个载体

last <- c("DOE", "VAN DYKE", "SMITH") 

first <- c("John", "Dick", "Mary Jane")

非常感谢任何帮助。感谢。

2 个答案:

答案 0 :(得分:2)

这应该有效:

# Define a pattern that only matches words composed entirely of capital letters
pat <- paste("^[", paste(LETTERS, collapse=""), "]*$", sep="")
# [1] "^[ABCDEFGHIJKLMNOPQRSTUVWXYZ]*$"

names <- c("DOE John", "VAN DYKE Dick", "SMITH Mary Jane") 
splitNames <- strsplit(names, " ")

# LAST NAMES: (Extract and paste together words matching 'pat')
sapply(splitNames, 
       function(X) paste(grep(pat, X, value=TRUE), collapse=" "))
# [1] "DOE"      "VAN DYKE" "SMITH" 

# First Names: (Extract and paste together words NOT matching 'pat')
sapply(splitNames, 
       function(X) paste(grep(pat, X, value=TRUE, invert=TRUE), collapse=" "))
# [1] "John"      "Dick"      "Mary Jane"

要匹配所有大写字母,您也可以使用字符类[:upper:],如:

pat <- "^[[:upper:]]*$"

虽然?regexp的文件似乎温和地警告不要这样做,理由是便携性降低。

答案 1 :(得分:1)

这里有一种方式:

l <- strsplit(names," ")
splitCaps <- function(x){
    ind <- x == toupper(x)
    list(upper = paste(x[ind],collapse = " "),
         lower = paste(x[!ind],collapse = " "))
}

> lapply(l,splitCaps)
[[1]]
[[1]]$upper
[1] "DOE"

[[1]]$lower
[1] "John"


[[2]]
[[2]]$upper
[1] "VAN DYKE"

[[2]]$lower
[1] "Dick"


[[3]]
[[3]]$upper
[1] "SMITH"

[[3]]$lower
[1] "Mary Jane"

请注意,如果您开始混合使用不常见的字符集,区域设置,符号,那么大量警告使用toupper挑选所有大写字词将非常不可靠等等。但对于非常简单的ASCII类型情况,它应该可以正常工作。

相关问题