在mutate dplyr中使用row_number()作为列表索引

在mutate dplyr中使用row_number()作为列表索引,r,indexing,dplyr,mutate,R,Indexing,Dplyr,Mutate,我正在尝试使用数据帧的row_number()作为每一行的索引。其思想是使用此索引访问特定的列表元素 dataset <- data %>% mutate(index = row_number()) %>% mutate(Y = strsplit(date, split = " ")[[index]][1]) 如果没有任何数据或可复制的例子,很难回答这个问题,所以我猜这就是作者想要的。(如果是,则索引变量是不必要的,并且dplyr::rowwise

我正在尝试使用数据帧的row_number()作为每一行的索引。其思想是使用此索引访问特定的列表元素

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

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

库(dplyr)
图书馆(tibble)
图书馆(stringr)
虹膜[c(1:3),]%>%
TIBLE::行名到列(df=,var=“index”)%>%
dplyr::行(数据=)%%>%
dplyr::mutate(.data=。,
Y=stringr::str_split(string=Species,pattern=“o”)[[1]][1])
#>来源:本地数据帧[3 x 7]
#>小组:
#> 
#>#tibble:3 x 7
#>指数萼片。长萼片。宽花瓣。长花瓣。宽种Y
#>                                     
#>1 5.10 3.50 1.40 0.200 setosa一套
#>2 4.90 3.00 1.40 0.200 setosa套装
#>3 4.70 3.20 1.30 0.200 setosa套件

我很确定这也会起作用:

dataset <- data %>% 
  mutate(Y = lapply(row_number(), function(x) strsplit(date, split = " ")[[x]][1])) 
dataset%
变异(Y=lappy(行号(),函数(x)strsplit(日期,split=”“)[[x]][1]))

仍然:
在mutate\u impl(.data,dots)中出错:评估错误:在级别1中没有这样的索引。
应该注意:日期是一列。@incodeveritas您可以提供一个示例,说明如何处理数据子集或内置R中的其他数据集吗?我最后在这里发布了更多信息。row_wise()解决了我的问题@incodeveritas这也是我发布的解决方案,当然只是基于对你想要什么的猜测。
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
dataset <- data %>% 
  mutate(Y = lapply(row_number(), function(x) strsplit(date, split = " ")[[x]][1]))