[英]Merge two columns in R while replacing when value is not present in other column
我想合並我的數據集的兩列,這兩列的性質是/或,即如果一個列中存在一個值,它將不會出現在另一列中。 我嘗試了這些
temp<-list(a=1:3,b=10:14)
paste(temp$a,temp$b)
產量
"1 10" "2 11" "3 12" "1 13" "2 14"
和這個
temp<-list(a=1:3,b=10:14,c=20:25)
temp<-within(temp,a <- paste(a, b, sep=''))
產量
temp$a
[1] "110" "211" "312" "113" "214"
但是我正在尋找的是替換不存在的值。 例如temp $
a僅具有1:3,而temp
$ b具有10:14,即兩個額外的值-所以我希望我的答案是
1_10 2_11 3_12 _13 _14
編輯-請看,我不希望列c
與a
和$b
串聯
使用stri_list2matrix
,我們可以用''
fill
長度較短的列表元素,並使用paste
。
library(stringi)
do.call(paste, c(as.data.frame(stri_list2matrix(temp, fill='')), sep='_'))
#[1] "1_10" "2_11" "3_12" "_13" "_14"
stri_list2matrix(temp, fill='')
用''
填充length
較短的列表元素后,將list
轉換為matrix
。 將其轉換為data.frame
( as.data.frame
),並使用do.call(paste
到paste
元件分隔各行中_
( sep='_'
)。
如果您只對“ temp”的前兩個元素感興趣,則基於編輯的“ temp”
do.call(paste, c(as.data.frame(stri_list2matrix(temp[1:2], fill='')),
sep='_'))
#[1] "1_10" "2_11" "3_12" "_13" "_14"
您還可以按names
來子集。 temp[c('a', 'b')]
擴展較短向量的長度以匹配較長向量的長度,然后粘貼:
paste(c(temp$a,rep("",length(temp$b)-length(temp$a))), temp$b, sep="_")
#[1] "1_10" "2_11" "3_12" "_13" "_14"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.