使用哪个函数的 dplyr 等效项是什么?

What is a dplyr equivalent for using which function?

我有一个数据框 1:

df1<- structure(list(`gaugelist[1:20, ]` = c(1094000L, 1094000L, 1094000L, 
1100600L, 1100600L, 1100600L, 1100600L, 1100600L, 1100600L, 1100600L, 
1100600L, 1100600L, 1100600L, 1100600L, 1096000L, 1100600L, 1100600L, 
1100600L, 1100600L, 1100600L)), .Names = "gaugelist[1:20, ]", row.names = c(NA, 
-20L), class = "data.frame")

第二个列表:

df2 <- c("ts.01094000.crest.csv", "ts.01100600.crest.csv")

我想根据匹配的行值在 df1 中创建另一列:

df1$test <- apply(df1, 1, function(x) df2[which(grepl(x,df2))])
  1. 完成这项工作的 dplyr 方法是什么?我无法按行工作。
  2. 如果 df1 有大量列并且我只想根据相同规则添加一个新列 'test',我该如何进行这项工作。

这对我有用:

df1 <- setNames(df1, "x") # rename column to `x` for brevity
df1 %>% rowwise() %>%
 mutate(test = df2[grep(x,df2)[1]])
# Source: local data frame [20 x 2]
# Groups: <by row>

# # A tibble: 20 × 2
#          x                  test
#      <int>                 <chr>
# 1  1094000 ts.01094000.crest.csv
# 2  1094000 ts.01094000.crest.csv
# 3  1094000 ts.01094000.crest.csv

解释。你没有解释为什么你"couldn't make rowwise work",但根据我自己的经验,你可能已经收到这条消息

Error: incompatible size (0), expecting 1 (the group size) or 1

如果您在 mutate 中使用类似 df2[which(grepl(x,df2))] 的表达式,这是因为一个(或多个)返回值的长度为 0(即在 df2 中未找到匹配项) ).使用 mutate(test = df2[grep(x,df2)[1]]) 解决了这个问题。特别要注意 df2[grep(x,df2)[1]] returns 一个且只有一个值。