【问题标题】:Paste all combinations of two separate vectors in R [duplicate]将两个单独向量的所有组合粘贴到 R [重复]
【发布时间】:2017-05-02 08:58:37
【问题描述】:

我有两个向量

df1 <- c("a","b","c")
df2 <- c("1","2","3")

 # expected output
 #  a1 a2 a3 b1 b2 b3 c1 c2 c3

我见过Paste all combinations of a vector in R,但是,这并不能解决我的困境。

【问题讨论】:

  • 试试:as.vector(t(outer(c("a","b","c"),c(1,2,3),'paste0')))

标签: r vector combinations paste


【解决方案1】:

另一种方法:

df1 <- c("a","b","c")
df2 <- c("1","2","3")

apply(expand.grid(df1, df2), 1, paste, collapse="")

【讨论】:

  • 或者干脆do.call(paste0, expand.grid(df1, df2))
【解决方案2】:

你可以merge:apply(merge(df1, df2), 1, function(row) paste(row[1], row[2], sep = ''))

【讨论】:

    【解决方案3】:

    像这样:

    paste0(rep(df1, length(df1)), rep(df2, length(df2)))
    

    或者这个:

    df_comb <- expand.grid(df1, df2)
    paste0(df_comb$Var1, df_comb$Var2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-31
      • 2018-03-10
      相关资源
      最近更新 更多