Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 我想用以前的非NA值和“替换表中的NA”;“未分类”;_R - Fatal编程技术网

R 我想用以前的非NA值和“替换表中的NA”;“未分类”;

R 我想用以前的非NA值和“替换表中的NA”;“未分类”;,r,R,使用R:我需要用最接近左边的值和“未分类的”填充任何NA单元格 下面的代码可以完美地填充最接近左边的值,但我不知道如何在前面放置永久字符串“Unclassified” 我想: a b c 2 unclassifed_2 1 2 2 1 1 unclassifed_1 5 1 1 2 1 1 un

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

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

我想:

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  

您可以使用粘贴和索引。这个循环就可以了

for( i in 1:ncol(x)){

if( any( is.na(  x[, i ]))){
x[ is.na( x[ , i ] )  , i ] <- 
    paste0( "unclassified_", x[ is.na( x[ , i ] )  , i-1 ] )
}
} 
for(1中的i:ncol(x)){
如果(有(is.na(x[,i])){

x[is.na(x[,i]),i]您可以使用粘贴和索引。这个循环可以实现这一点

for( i in 1:ncol(x)){

if( any( is.na(  x[, i ]))){
x[ is.na( x[ , i ] )  , i ] <- 
    paste0( "unclassified_", x[ is.na( x[ , i ] )  , i-1 ] )
}
} 
for(1中的i:ncol(x)){
如果(有(is.na(x[,i])){

你的问题比我的答案复杂。我以后会试着修改。你的问题比我的答案复杂。我以后会试着修改。
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  
x$b[is.na(x$b)] = paste0("unclassifed_", x$a)
x$c[is.na(x$c)] = paste0("unclassifed_", x$a)
for( i in 1:ncol(x)){

if( any( is.na(  x[, i ]))){
x[ is.na( x[ , i ] )  , i ] <- 
    paste0( "unclassified_", x[ is.na( x[ , i ] )  , i-1 ] )
}
}