|
两张行列相同的表格,用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.
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-9-27 06:54
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社