【问题标题】:How to get access to "str_match_all" results in R?如何在 R 中访问“str_match_all”结果?
【发布时间】:2022-07-20 23:29:34
【问题描述】:

刚才使用“str_match_all”如下:

a <- str_match_all(dd, '\\d+(\\w+)')`

并获得以下信息:

#[[1]]
#     [,1]      [,2]   
#[1,] "12hours" "hours"
#[2,] "23days"  "days"

如何访问每个字符串?

例如,我尝试使用 a[1][,1] 访问第一列,但我收到一条错误消息,指出维度数不正确。

【问题讨论】:

  • 打印清楚地显示[[1]]。使用a[[1]][, 1]

标签: r string dimensions


【解决方案1】:

如果我正确理解了您的问题,那么您在访问每个单独的元素时都会遇到问题。

我认为您必须记住,您的输出是一个列表,而该列表中的元素是一个矩阵。因此,要访问每个单独的元素,您首先必须调用列表中您感兴趣的元素,然后调用行和列。

a[[1]][1,2]

所以在你的情况下,这将访问你列表中的第一个元素(看起来你只有 1 个),然后是第一行,然后是第二列,所以它会给你“小时”。

但是,如果您更习惯于使用数据框(我认为这是您的最终目标),我会以编程方式处理此问题,如下所示:

以str_match_all() 文档为例

# Creating reproduceable example
strings <- c("Home: 219 733 8965.  Work: 229-293-8753 ",
             "banana pear apple", "595 794 7569 / 387 287 6718")
phone <- "([2-9][0-9]{2})[- .]([0-9]{3})[- .]([0-9]{4})"

您的目标是将矩阵转换为数据框。你这样做如下

as.data.frame(a[[1]])

为了将来参考,假设您的输出超过 1 个元素,就像本示例中的情况一样,您应该像这样处理解决方案:

# Make a function that accepts your list variable. 
# Copy and paste the step before and then add an extra step using dplyr::bind_rows()

output_to_df <- function(x){
   a <- as.data.frame(x)
   bind_rows(a)
}
# Using this function we will then use map_dfr() 
# so that we can apply our premade function on all elements
# of our list no matter how many elements it contains

str_output <- map_df(a, output_to_df)

您现在可以根据需要多次重复使用 output_to_df() 函数。

【讨论】:

    猜你喜欢
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多