我正在尝试使用我的数据帧的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 .
答案 0 :(得分: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
答案 1 :(得分:0)
我很确定这也可以:
dataset <- data %>%
mutate(Y = lapply(row_number(), function(x) strsplit(date, split = " ")[[x]][1]))