tony8310的个人博客分享 http://blog.sciencenet.cn/u/tony8310

博文

两张相同的表格,替换相应位置NA值

已有 536 次阅读 2023-11-6 10:31 |系统分类:科研笔记

两张行列相同的表格,用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

上一篇:网页数据下载的一些操作
下一篇:根据映射关系查找替换
收藏 IP: 202.113.99.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-28 00:38

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部