【问题标题】:Using row_number() as list index in mutate dplyr使用 row_number() 作为 mutate dplyr 中的列表索引
【发布时间】:2018-02-13 21:31:07
【问题描述】:

我正在尝试使用我的数据框的 row_number() 作为每一行的索引。这个想法是使用这个索引来访问特定的列表元素。

dataset <- data %>% 
      mutate(index = row_number()) %>%
      mutate(Y = strsplit(date, split = " ")[[index]][1]) 

简而言之,对于每一行,我想使用它的行索引从另一个列表中获取特定的字符串元素。

这会引发索引错误:

Error in mutate_impl(.data, dots) : Evaluation error: recursive indexing failed at level 2 .

【问题讨论】:

    标签: r indexing dplyr


    【解决方案1】:

    如果没有任何数据或可重复的例子,很难回答这个问题,所以这就是我猜测作者想要的。 (如果是,那么index 变量是不必要的,dplyr::rowwise() 是您所需要的):

    library(dplyr)
    library(tibble)
    library(stringr)
    
    iris[c(1:3),] %>%
      tibble::rownames_to_column(df = ., var = "index") %>%
      dplyr::rowwise(data = .) %>%
      dplyr::mutate(.data = .,
                    Y = stringr::str_split(string = Species, pattern = "o")[[1]][1])
    #> Source: local data frame [3 x 7]
    #> Groups: <by row>
    #> 
    #> # A tibble: 3 x 7
    #>   index Sepal.Length Sepal.Width Petal.Length Petal.Width Species Y    
    #>   <chr>        <dbl>       <dbl>        <dbl>       <dbl> <fct>   <chr>
    #> 1 1             5.10        3.50         1.40       0.200 setosa  set  
    #> 2 2             4.90        3.00         1.40       0.200 setosa  set  
    #> 3 3             4.70        3.20         1.30       0.200 setosa  set
    

    【讨论】:

    • 静止:Error in mutate_impl(.data, dots) : Evaluation error: no such index at level 1 .
    • 应注意:日期是一列。
    • @incodeveritas 您能否提供一个示例,说明您希望如何处理数据子集或 R 中内置的其他数据集?
    • 我最终在这里发布了更多信息。 row_wise() 解决了我的问题stackoverflow.com/questions/48778309/…
    • @incodeveritas 这也是我发布的解决方案,当然只是基于你想要的猜测。
    【解决方案2】:

    我很确定这也可以:

    dataset <- data %>% 
      mutate(Y = lapply(row_number(), function(x) strsplit(date, split = " ")[[x]][1])) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-17
      • 2014-03-12
      相关资源
      最近更新 更多