[英]Extracting names from the data frame as separate data in R
我有一個帶有姓名和姓氏的示例數據框。 我需要將名稱提取為單獨的數據。 我有想法為每個名稱一個一個地做這個,但是數據集很大,我需要一個更快的方法。 你能幫助我嗎?
df<-data.frame(name = c("John Smith", "Antonio Gilbert", "Rickie Hooley", "John Marquez", "Christian Thompson", "Rickie Galvan"),
telephone = c("234324", "2342343", "547547", "68656486", "5686686", "4664546"))
John <- df[grep("John", df$name), 1]
Rickie <- df[grep("Rickie", df$name), 1]
如果要根據名稱分隔數據框,我們可以先提取名字,然后對其進行split
。
output <- split(df, sub("\\s.*", "", df$name))
output
#$Antonio
# name telephone
#2 Antonio Gilbert 2342343
#$Christian
# name telephone
#5 Christian Thompson 5686686
#$John
# name telephone
#1 John Smith 234324
#4 John Marquez 68656486
#$Rickie
# name telephone
#3 Rickie Hooley 547547
#6 Rickie Galvan 4664546
所以現在你有了可以通過output$Antonio
、 output$Christian
等訪問的數據框列表。
這將生成一個數據框列表,每個數據框都包含一個不同的名字。 您可以使用dflist$John
等訪問它們。
firstnames <- unique(gsub("\\s.*$", "", df$name))
dflist <- lapply(firstnames, function(x) df[grep(x, df$name), 1, drop = FALSE])
names(dflist) <- firstnames
dflist
$John
name
1 John Smith
4 John Marquez
$Antonio
name
2 Antonio Gilbert
$Rickie
name
3 Rickie Hooley
6 Rickie Galvan
$Christian
name
5 Christian Thompson
我們可以使用dplyr
中的group_split
library(dplyr)
library(stringr)
df %>%
group_split(nameGroup = str_remove(name, "\\s.*"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.