张兵
两张相同的表格,替换相应位置NA值
2023-11-6 10:31
阅读:887

两张行列相同的表格,用r_table表格中的数据,替换table中相应位置的NA值 

具体实现过程如下:

- 找到table中为NA的位置,保存在一个数据框nas中。
- 遍历nas的每一行,获取行索引r和列索引s。
- 将r_table中对应位置的值赋给table中的对应位置。
- 返回替换了NA的新表格。

rna_df <- function(table, r_table) {
    # Table中NA所在行列
    nas <- which(is.na(table), arr.ind = TRUE) %>% as.data.frame()
    # 用data的数据赋值new中的NA
    for (i in 1:nrow(nas)) {
      r <- nas[i, 1]
      s <- nas[i, 2]
      table[r, s] <- r_table[r, s]
    }
    return(table)
  }
  new2 <- rna_df(new, data)


Two tables with the same number of rows and columns. Replace the NA values in the table with the corresponding values from the r_table.

The function rna_df(table, r_table) takes two tables, table and r_table, as input. Both tables have the same number of rows and columns. The function returns a new table.

Here is the implementation:

- Find the positions in table where the values are NA and save them in a data frame nas.
- Iterate over each row in nas and get the row index r and column index s.
- Assign the corresponding value from r_table to the corresponding position in table.
- Return the new table with the NA values replaced.


转载本文请联系原作者获取授权,同时请注明本文来自张兵科学网博客。

链接地址:https://wap.sciencenet.cn/blog-331295-1408626.html?mobile=1

收藏

分享到:

当前推荐数:0
推荐到博客首页
网友评论0 条评论
确定删除指定的回复吗?
确定删除本博文吗?