1

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

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  
4

3 回答 3

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用来替换Us:

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
于 2013-01-21T16:15:31.653 回答
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 )
}
于 2013-01-21T16:18:07.683 回答
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
于 2013-01-21T16:20:11.650 回答