我有以下数据集
dts1 <- data.frame (id = c(1,2,3,2,1), transactionID =c ("A","","", "B","A"))
我希望复制所有这些的transactionID值
所以我想转换一下:
id transactionID
1 1 A
2 2
3 3
4 2 B
5 1 A
到
id transactionID
1 1 A
2 2 B
3 3
4 2 B
5 1 A
这是我理想的输出 因为在第二行中错过了id 2的transactionID而我将其替换掉了。
我试过这个
library(dplyr)
dts1 %>% group_by(id) %>% mutate(transactionID = paste(transactionID, collapse=""))
这给了我以下内容:
id transactionID
(dbl) (chr)
1 1 AA
2 2 B
3 3
4 2 B
5 1 AA
答案 0 :(得分:1)
我们可以使用data.table
library(data.table)
setDT(dts1)[, transactionID := if(all(!nzchar(as.character(transactionID)))) transactionID
else transactionID[nzchar(as.character(transactionID))][1], by = id]
dts1
# id transactionID
#1: 1 A
#2: 2 B
#3: 3
#4: 2 B
#5: 1 A
答案 1 :(得分:1)
基础R /匹配:
lookup <- unique(dts1[dts1$transactionID != '',])
dts1$transactionID <- lookup[match(dts1$id, lookup[,1]),2]
dts1$transactionID[is.na(dts1$transactionID)] <- ''
dts1
id transactionID
1 1 A
2 2 B
3 3
4 2 B
5 1 A