首页 > 解决方案 > 我想用以前的非 NA 值和“Unclassified_”替换表中的 NA

问题描述

使用 R:我需要用最接近左侧的值以及“未分类_”填充任何 NA 单元格

下面的代码完美地填充了左边最接近的值,但我不知道如何在之前放置永久字符串“Unclassified_”

library(zoo)
y <-  t(na.locf(t(x), fromLast=F)) #Fill NA cells with closest value to the left

示例数据

set.seed(1)
x <- data.frame(a=sample(c(1,2), 10, replace=T),
                b=sample(c(1,2,NA), 10, replace=T), 
                c=sample(c(1:5,NA), 10, replace=T))

给出df:

a   b   c
2   NA  1       
2   2   1       
1   NA  5       
1   1   2       
1   1   NA      
1   NA  4       
1   1   5       
2   2   NA      
2   2   NA      
1   NA  2   

而且我要:

a       b            c
2   unclassifed_2    1      
2   2                1      
1   unclassifed_1    5      
1   1                2      
1   1                unclassified_1     
1   unclassified_1   4      
1   1                5      
2   2                unclassified_2     
2   2                unclassified_2         
1   unclassified_1   2  

标签: r

解决方案


x$b[is.na(x$b)] = paste0("unclassifed_", x$a)
x$c[is.na(x$c)] = paste0("unclassifed_", x$a)

推荐阅读