用R中的特定行均值替换缺失值或字符

时间:2013-01-21 15:41:52

标签: r replace

我想用行均值替换数据中的缺失值或字符值。例如,在下面的数据中,缺失值用“U”表示,我想用p1到p6中的所有“U”替换每行的“ave”列中的值。有数千行要替换。

num p1 p2 p3 p4 p5 p6   ave

L1  0  10 1  U  0  -10   1.3

L2  10  1 10 10 U  10    7.1

L3  U  10 10  U 1  -10   3.1  

3 个答案:

答案 0 :(得分:1)

数据:

df<-read.table(text="num p1 p2 p3 p4 p5 p6   ave
L1  0  10 1  U  0  -10   1.3
L2  10  1 10 10 U  10    7.1
L3  U  10 10  U 1  -10   3.1  ", header = TRUE)

您可以使用apply替换U s:

as.data.frame(t(apply(df, 1, function(x) replace(x, x == "U", tail(x, 1)))))

  num  p1 p2 p3  p4  p5  p6 ave
1  L1   0 10  1 1.3   0 -10 1.3
2  L2  10  1 10  10 7.1  10 7.1
3  L3 3.1 10 10 3.1   1 -10 3.1

答案 1 :(得分:0)

在r语言中通常不鼓励for循环,所以sven的答案更好,但这是一种直接的方式来做你想做的事情。

# example data table
mtcars

# here's how to access all the columns below two in the first row
mtcars[ 1 ,  mtcars[ 1 , ] < 2 ]

# here's how to take the mean of all columns at or above two in the first row
rowMeans( mtcars[ 1 ,  mtcars[ 1 , ] >= 2 ] , na.rm = T )

# here's how to overwrite the values below two with the mean of all columns at or above two
mtcars[ 1 ,  mtcars[ 1 , ] < 2 ] <- rowMeans( mtcars[ 1 ,  mtcars[ 1 , ] >= 2 ] , na.rm = T )


# run this command for every row, and you're done
for ( i in seq( nrow( mtcars ) ) ){
    mtcars[ i ,  mtcars[ i , ] < 2 ] <- 
        rowMeans( mtcars[ i ,  mtcars[ i , ] >= 2 ] , na.rm = T )
}

答案 2 :(得分:0)

这是一种方法:

mydf <- read.table(
  header = TRUE, stringsAsFactors = FALSE, 
  text = "num p1 p2 p3 p4 p5 p6   ave
          L1  0  10 1  U  0  -10   1.3
          L2  10  1 10 10 U  10    7.1
          L3  U  10 10  U 1  -10   3.1")

cbind(mydf[1], 
      t(apply(mydf[-1], 1, 
              function(x) ifelse(x == "U", x["ave"], x))))
#   num  p1 p2 p3  p4  p5  p6 ave
# 1  L1   0 10  1 1.3   0 -10 1.3
# 2  L2  10  1 10  10 7.1  10 7.1
# 3  L3 3.1 10 10 3.1   1 -10 3.1