2017-07-06 43 views
0

這裏是我的示例:串聯串的兩個列表和r中附上指數

stringa = c("a","b","c") 
stringb = c("high","low","average") 
index = c(1,2,3) 

data <- data.frame(stringa,stringb,index) 

我想串聯stringa和stringb,而在另一列附上相應的索引。例如,結果的第一行應該是索引爲「1」的「高」。

現在我已經使用這個功能來連接兩個字符串:

c(outer(a, b, paste)) 
+0

發生了什麼事?這是不是預期? –

回答

1

爲 「高」, 「B低」, 「C平均」 你可以這樣做:

stringa = c("a","b","c") 
stringb = c("high","low","average") 
index = c(1,2,3) 
data.frame(concatenated = paste(stringa, stringb),index) 
    concatenated 
1 a high 
2 b low 
3 c average 

對於stringa和stringb的全排列:

stringa = c("a","b","c") 
stringb = c("high","low","average") 
data.frame(concatenated = c(outer(stringa, stringb, paste))) 
    concatenated 
1  a high 
2  b high 
3  c high 
... 
9 c average 

如果要明確添加行索引:

df = data.frame(concatenated = c(outer(stringa, stringb, paste))) 
df$index = rownames(df) 
df 
    concatenated index 
1  a high  1 
2  b high  2 
3  c high  3 
... 
9 c average  9 
+0

我還需要將「a」與「低」和「平均」 –