我有一个包含五列的数据帧Df,第五列(TypeWire(是前两列的连接,以使事情变得更简单。对于每种类型(如A(,都应该有"陆地"one_answers"WiFi",但在我的数据帧中,一些类型的数据帧丢失了(例如,D和B的WiFi丢失(。现在,如果Type缺少任何Wire,我如何添加行?为了使事情变得简单,添加了TypeWire列。我可以手动将其添加到数据帧中,但我正在寻找它可以自动检测并添加行的方法(例如=B WiFI 0 BWiFi(我试着只为类型B和D创建下面的函数(如果th,但它正在添加条目,即使它像BL一样存在于TypeWire列中,并且在TypeWire中,但它的行仍然是由下面的函数创建的。
Missadd2<-function(x){
if(any(!(x$TypeWire == 'DWiFi'))){
x <- rbind(x, newrow<-c("D","WiFi",0,0,"DWiFi"))
}else if(any(!(x$TypeWire == 'BWiFi'))){
x <- rbind(x, newrow<-c("B","WiFi",0,0,"BWiFi"))
}else if(any(!(x$TypeWire == 'BLand'))){
x <- rbind(x, newrow<-c("B","Land",0,0,"BLand"))
}
}
Df
我不完全确定这是否是您想要的。
您可以使用tidyr
包中的complete
来提供缺少的Type
和Wire
的组合,因此您应该同时拥有";土地;以及";WiFi";对于所有类型。您可以使用值列表指定fill
,以包括添加的新行中缺少的元素。
library(tidyr)
df %>%
complete(Type, Wire, fill = list(Value = 0, Count = 0)) %>%
mutate(TypeWire = paste0(Type, Wire))
输出
# A tibble: 10 x 5
Type Wire Value Count TypeWire
<chr> <chr> <dbl> <dbl> <chr>
1 A Land 500 10 ALand
2 A WiFi 89 2 AWiFi
3 B Land 125 5 BLand
4 B WiFi 0 0 BWiFi
5 C Land 300 6 CLand
6 C WiFi 100 1 CWiFi
7 D Land 425 1 DLand
8 D WiFi 0 0 DWiFi
9 O Land 8150 22 OLand
10 O WiFi 0 0 OWiFi
数据
df <- structure(list(Type = c("A", "A", "B", "C", "C", "D", "O"), Wire = c("Land",
"WiFi", "Land", "Land", "WiFi", "Land", "Land"), Value = c(500,
89, 125, 300, 100, 425, 8150), Count = c(10, 2, 5, 6, 1, 1, 22
)), class = "data.frame", row.names = c(NA, -7L))