连接两列中的每个值

时间:2019-06-17 15:21:38

标签: r loops concat string-concatenation

我有两列需要联系其值。例如,我有“颜色”(黑色,蓝色,红色,紫色,黄色)和“服装”(连衣裙,鞋子,T恤,长衫)列。然后,我想穿黑色连衣裙,黑色鞋子,黑色T恤,黑色长衫,蓝色连衣裙,蓝色鞋子,蓝色T恤等)

我已经尝试过使用for循环和粘贴功能,但是它没有按照我希望的那样工作。

A <- colour
B <- Clothing

 for(i in count(A)){ paste( print(A[i]) ,
             for (i in count(B)) {print(B[i])} 
      )
    }

2 个答案:

答案 0 :(得分:1)

如果要矩阵:

> sapply(A,function(x) paste(x,B))
     Black              Blue              Red              Purple              Yellow             
[1,] "Black Dress"      "Blue Dress"      "Red Dress"      "Purple Dress"      "Yellow Dress"     
[2,] "Black Shoe"       "Blue Shoe"       "Red Shoe"       "Purple Shoe"       "Yellow Shoe"      
[3,] "Black T-shirt"    "Blue T-shirt"    "Red T-shirt"    "Purple T-shirt"    "Yellow T-shirt"   
[4,] "Black Long-shirt" "Blue Long-shirt" "Red Long-shirt" "Purple Long-shirt" "Yellow Long-shirt"

向量:

> as.vector(sapply(A,function(x) paste(x,B)))
 [1] "Black Dress"       "Black Shoe"        "Black T-shirt"     "Black Long-shirt"  "Blue Dress"        "Blue Shoe"        
 [7] "Blue T-shirt"      "Blue Long-shirt"   "Red Dress"         "Red Shoe"          "Red T-shirt"       "Red Long-shirt"   
[13] "Purple Dress"      "Purple Shoe"       "Purple T-shirt"    "Purple Long-shirt" "Yellow Dress"      "Yellow Shoe"      
[19] "Yellow T-shirt"    "Yellow Long-shirt"

答案 1 :(得分:0)

我们可以使用outer

outer(A, B, FUN = paste)
#  [,1]           [,2]          [,3]             [,4]               
#[1,] "Black Dress"  "Black Shoe"  "Black T-shirt"  "Black Long-shirt" 
#[2,] "Blue Dress"   "Blue Shoe"   "Blue T-shirt"   "Blue Long-shirt"  
#[3,] "Red Dress"    "Red Shoe"    "Red T-shirt"    "Red Long-shirt"   
#[4,] "Purple Dress" "Purple Shoe" "Purple T-shirt" "Purple Long-shirt"
#[5,] "Yellow Dress" "Yellow Shoe" "Yellow T-shirt" "Yellow Long-shirt"

或者使用map中的purrr

library(purrr)
map(A, ~ str_c(.x, B, sep= " ")) %>%
      flatten_chr
#[1] "Black Dress"       "Black Shoe"        "Black T-shirt"     "Black Long-shirt"  "Blue Dress"        "Blue Shoe"        
#[7] "Blue T-shirt"      "Blue Long-shirt"   "Red Dress"         "Red Shoe"          "Red T-shirt"       "Red Long-shirt"   
#[13] "Purple Dress"      "Purple Shoe"       "Purple T-shirt"    "Purple Long-shirt" "Yellow Dress"      "Yellow Shoe"      
#[19] "Yellow T-shirt"    "Yellow Long-shirt"

数据

A <- c("Black", "Blue", "Red", "Purple", "Yellow")
B <- c("Dress", "Shoe", "T-shirt", "Long-shirt")