https://campus.datacamp.com/courses/intermediate-r-practice/utilities?ex=5
这个练习不会做,在这里记录一下答案。
数据:
titanic 数据里面 Name 一列:
[888] "Graham, Miss. Margaret Edith"
[889] "Johnston, Miss. Catherine Helen \"Carrie\""
[890] "Behr, Mr. Karl Howell"
[891] "Dooley, Mr. Patrick"
任务:
提取出每个人名中的 title,也就是上面代码中的 “Mr” “Miss” 部分。
# Extract the name column from titanic
pass_names <- titanic$Name
# Create titles
titles <- gsub("^.*, (.*?)\\..*$", "\\1", pass_names)
# Call unique() on titles
unique(titles)
难点——正则表达式
() 括号的作用:可以在 replace 时重复使用。
With , (.*?)\\.
we use a similar pattern as before, but the parentheses allow us to re-use whatever is matched inside the parentheses in our replacement.
"\\1"
的作用:使用括号中的内容 replace 前面整个字符串。
The "\\1"
part tells R to replace the entire string with whatever is matched inside the parentheses.
一个例子,理解 \1 的用法:
gsub("(.*?)\\s(.*?)\\s(.*?)(\\?)$", "\\3 \\1 \\2\\4", "are you ready?")
[1] "ready are you?"