我正在使用这样的脚本收集一些数据:
library(tidyverse)
library(rvest)
library(magrittr)
library(stringr)
foo_matrix <- read_html("#address")
test <- foo_matrix %>%
html_nodes(#Retrieval Information) %>%
html_text() %>%
str_trim
它返回的输出如下所示:
1“红队”"Mike Johnson“"QB”"6-1“"191”6 "99“"21”"2“"5”“乔·史密斯”11 "OT“"6-3”"290“"98”"55“16 "3”"1“
我想要做的是提取字符串中的第一个值("Red“),然后将剩下的数据作为这样的8列矩阵来创建:
Mike Johnson QB 6-1 191 99 21 2 5
Joe Smith OT 6-3 290 98 55 3 1
但是,我想要创建第九列,该列从最初提取的字符串中获取值,并将其应用于所有行,因此最终结果如下:
Mike Johnson MD 6-1 191 99 21 2 5 Red Team
Joe Smith VA 6-3 290 98 55 3 1 Red Team
最好的方法是什么?)(提取值,然后取b.)将它作为第九列遍历所有行?
发布于 2018-02-15 15:53:33
也许有更干净的方法可以做到这一点。
假设团队始终是第一个元素,您可以首先将团队与人员数据分离开来。
然后假设您的人员数据总是有8列,您可以在列表中split
它们,并使用as_tibble
和bind_rows
在唯一的data.frame中转换结果。
最后,使用add_column
添加团队。mutate
也应该做到这一点。
library(stringr)
library(purrr)
library(tibble)
library(dplyr)
data <- c("Red Team", "Mike Johnson", "QB" ,"6-1","191",
"99" ,"21" ,"2","5","Joe Smith" ,
"OT" ,"6-3" , "290" , "98" ,"55",
"3" ,"1")
team <- data[1]
people <- data[-1]
resulting_df <- people %>%
split(ceiling(seq_along(people)/8)) %>%
map(~ as_tibble(t(.x))) %>%
bind_rows() %>%
add_column(team = team)
resulting_df
#> # A tibble: 2 x 9
#> V1 V2 V3 V4 V5 V6 V7 V8 team
#> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
#> 1 Mike Johnson QB 6-1 191 99 21 2 5 Red Team
#> 2 Joe Smith OT 6-3 290 98 55 3 1 Red Team
https://stackoverflow.com/questions/48810685
复制相似问题