什么是使用哪个函数的dplyr等价物?

时间:2016-09-29 01:47:44

标签: r dplyr apply

我有一个数据帧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包含大量列,并且我只想要一个新列&#39; test&#39;基于同样的规则。

1 个答案:

答案 0 :(得分:2)

这对我有用:

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

解释。您没有解释为什么您无法进行逐行工作&#34;,但根据我自己的经验,您可能已收到此消息

  

错误:大小不一致(0),期望1(组大小)或1

如果在df2[which(grepl(x,df2))]中使用mutate之类的表达式,则会因为一个(或多个)返回值的长度为0而发生(即df2中未找到匹配项)。使用mutate(test = df2[grep(x,df2)[1]])解决了这个问题。请特别注意df2[grep(x,df2)[1]]只返回一个值。

相关问题