【问题标题】:in R, how to separate start, middle, and of end of string when length of string is variable?在R中,当字符串长度可变时,如何分隔字符串的开始、中间和结尾?
【发布时间】:2021-10-06 06:58:03
【问题描述】:

例如我有这个,

Full Name
1 Fred Peters 
2 Fred Lukas Peters
3 Fred Lukas James Peters
4 Fred Lukas of James Peters

但想拥有,

First     Middle          Last
1 Fred                      Peters
2 Fred      Lukas           Peters
3 Fred      Lukas James     Peters
4 Fred      Lukas of James  Peters
5 Michael                   Smith

我知道如何使用 separate(Full Name, c("First","Middle","Last"), " ")

但是我很困惑如何告诉 R 字符串的最后一个单词应该始终在最后一列中,并且 First 和 Last 之间的所有内容都应该介于两者之间。

【问题讨论】:

  • 忽略第二个数据框中的第 5 个观察结果

标签: r string indexing


【解决方案1】:

我们可以使用extract

library(dplyr)
library(stringr)
library(tidyr)
df1 %>%
    mutate(`Full Name` = str_replace(`Full Name`, 
     '^(\\w+)\\s+(\\w+)$', "\\1 NA \\2")) %>%
     extract(`Full Name`, into = c("First","Middle","Last"), 
          "^(\\S+)\\s+(.*)?\\s+(\\S+)$", convert = TRUE)

-输出

   First         Middle   Last
1  Fred             NA Peters
2  Fred          Lukas Peters
3  Fred    Lukas James Peters
4  Fred Lukas of James Peters

数据

df1 <- structure(list(`Full Name` = c("Fred Peters", "Fred Lukas Peters", 
"Fred Lukas James Peters", "Fred Lukas of James Peters")), 
class = "data.frame", row.names = c("1", 
"2", "3", "4"))

【讨论】:

  • 谢谢!但是,这很有效,它消除了所有没有中间名的观察。我该如何解决这个问题?
猜你喜欢
  • 2020-03-11
  • 2020-06-11
  • 2018-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-10
  • 2021-03-30
  • 1970-01-01
相关资源
最近更新 更多