簡體   English   中英

當其他列中不存在值時替換R中的兩列

[英]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

編輯-請看,我不希望列ca$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.frameas.data.frame ),並使用do.call(pastepaste元件分隔各行中_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM