我在R中有以下数据帧,这是R
中某些代码的输出 Size total_weight
20 1829000
现在,我想要的是如果上面的数据帧中只有一行,那么我想将其他行添加为
Size total_weight
40 0
如果只有Size
20,那么我想添加Size =40 and total_weight =0
如果只有Size
40,那么我想添加Size =20 and total_weight =0
所需的数据框是
Size total_weight
20 1829000
40 0
我在r
中编写了以下代码if(dim(weight)[1] == 1){
if(weight$Size[1] == 20 & weight$total_weight[1] != 0){
weight$Size[2] = 40
weight$total_weight[2] = 0
}else{
weight$Size[2] = 20
weight$total_weight[2] = 0
}
}
但是,它会出现以下错误
Error in `$<-.data.frame`(`*tmp*`, Size, value = c(20, 40)) :
replacement has 2 rows, data has 1
答案 0 :(得分:1)
使用%in%
无需检查维度和嵌套的if
语句
df1 <- data.frame(Size = 20, total_weight = 1829000)
if (!20 %in% df1$Size) df1 <- rbind(df1, list(20, 0))
if (!40 %in% df1$Size) df1 <- rbind(df1, list(40, 0))
Size total_weight
1 20 1829000
2 40 0