我想在R

时间:2017-05-03 13:05:28

标签: r

我有2个向量。

1表示服务:

services <- c('service1', 'service2')
城市

1:

cities <- c('city1','city2','city3','city4','city5','city6')

我想将它们组合起来创建一个这样的列表:

c('city1 service1', 'city1 service2','city2 service1', 'city2 service2','city3 service1', 'city3 service2','city4 service1', 'city4 service2','city5 service1', 'city5 service2','city6 service1', 'city6 service2')

我想我必须使用apply,但我无法得到结果。抱歉这个愚蠢的问题。

感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

services <- c('service1', 'service2')
cities <- c('city1','city2','city3','city4','city5','city6')
n <- length(cities)
paste(cities, rep(services, each=n))

 [1] "city1 service1" "city2 service1" "city3 service1" "city4 service1" "city5 service1"
 [6] "city6 service1" "city1 service2" "city2 service2" "city3 service2" "city4 service2"
[11] "city5 service2" "city6 service2"

答案 1 :(得分:0)

您可以使用expand.grid然后使用paste

services <- c('service1', 'service2')
cities <- c('city1','city2','city3','city4','city5','city6')
tmp <- expand.grid(services, cities) 

paste(tmp$Var2, tmp$Var1)

答案 2 :(得分:0)

services <- c('service1', 'service2')
cities <- c('city1','city2','city3','city4','city5','city6')
df <- expand.grid(services, cities)
res <- paste(df[[1]], df[[2]])
res