以下是我拥有的一些数据的示例

 dput(df)
structure(list(ID = c("a", "b", "c", "d", "e", "f", "g", "h", 
"i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "b", 
"c", "d", "e", "f", "j", "k", "n", "m", "q", "r"), Number = c(1, 
2, 1, 3, 4, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 
1, 2, 1, 1, 1, 1, 1, 2, 2), Location = c(1, 1, 1, 1, 1, 1, 1, 
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 
2, 2, 2), Surveyor = c("JKK", "JKK", "JKK", "JKK", "JKK", "JKK", 
"JKK", "JKK", "JKK", "JKK", "JKK", "JKK", "JKK", "JKK", "JKK", 
"JKK", "JKK", "JKK", "JKK", "JKK", "JKK", "JKK", "JKK", "JKK", 
"JKK", "JKK", "JKK", "JKK", "JKK", "JKK", "JKK")), row.names = c(NA, 
-31L), spec = structure(list(cols = list(ID = structure(list(), class = c("collector_character", 
"collector")), Number = structure(list(), class = c("collector_double", 
"collector")), Location = structure(list(), class = c("collector_double", 
"collector")), Surveyor = structure(list(), class = c("collector_character", 
"collector"))), default = structure(list(), class = c("collector_guess", 
"collector")), delim = ","), class = "col_spec"), problems = <pointer: 0x00000253510611f0>, class = c("spec_tbl_df", 
"tbl_df", "tbl", "data.frame"))

在上面的例子中,我有col ID,它包含字母a—t(我的真实数据有其他字母代码),在Location1中,所有这些代码都存在.Location2年,其中一些人失踪了.

我想在遗漏身份证的Number栏中加0.

我的真实数据有25个位置,所以理想情况下,我希望能够抓住ID的完整列表,并对照每个位置判断,并在缺少的地方添加0.

我试过tidyverse::mutatecase_when个,但我没有任何进展.感谢任何帮助.

推荐答案

你可以用tidyr::complete()个.fill参数允许您设置创建的列中的值.

df  |> 
    tidyr::complete(
        ID,
        Location, 
        fill = list(Number = 0)
    )

对于新的值,输出将有0表示Number,而对于任何未显式设置的列(即Surveyor),输出将有NA表示.

输出

我把上面的内容赋给了一个名为new_df的变量,这样你就可以很容易地与原来的df进行比较:

dplyr::anti_join(new_df, df, by = c("ID", "Location"))

# A tibble: 9 × 4
  ID    Location Number Surveyor
  <chr>    <dbl>  <dbl> <chr>   
1 a            2      0 NA      
2 g            2      0 NA      
3 h            2      0 NA      
4 i            2      0 NA      
5 l            2      0 NA      
6 o            2      0 NA      
7 p            2      0 NA      
8 s            2      0 NA      
9 t            2      0 NA   

R相关问答推荐

将一个载体的值相加,直到达到另一个载体的值

变量计算按R中的行更改

为什么当我try 在收件箱中使用合并功能时会出现回收错误?

如何计算R数据集中每个女性的子元素数量?

将向量组合到一个数据集中,并相应地命名行

根据多个条件增加y轴高度以适应geom_text标签

R中插入符号训练函数的中心因子和尺度因子预测

R—将各种CSV数字列转换为日期

R中的时间序列(Ts)函数计数不正确

ComplexHEAT:使用COLUMN_SPLIT时忽略COLUMN_ORDER

在R中创建连续的期间

从多层嵌套列表构建Tibble?

R中Gamma回归模型均方误差的两种计算方法不一致

我是否可以使用多个变异项来构建顺序列(标记多个问题)

Ggplot2如何找到存储在对象中的残差和拟合值?

R try Catch in the loop-跳过缺少的值并创建一个DF,显示跳过的内容

将边列表转换为路径长度列表

从单个html段落中提取键-值对

R,将组ID分配给另一个观测ID变量中的值的组合

具有某些列的唯一值的数据帧