我在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
使用%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