【问题标题】:replace missing values or characters with the particular row mean in R用 R 中的特定行均值替换缺失值或字符
【发布时间】:2013-01-22 00:20:11
【问题描述】:

我想用行平均值替换数据中的缺失值或字符值。例如在下面的数据中,缺失值用“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  

【问题讨论】:

  • 您应该添加一个与您使用的语言相对应的标签(R?)。
  • 是的 - 没有关于您使用的语言的信息很难提供帮助。
  • 你能dput几行你的实际数据。 “ave”列是您的数据框的一部分吗?是否存在 both 缺失值和代表缺失值的“U”等字符?

标签: r replace


【解决方案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

【讨论】:

    【解决方案2】:

    这是一种方法:

    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
    

    【讨论】:

    • 文件在 .csv 中,但 R 将“U”更改为 NA,它如何与 NA 一起使用?
    • ifelse(is.na(x)...替换ifelse(x == "U"...
    【解决方案3】:

    在 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 )
    }
    

    【讨论】:

      猜你喜欢
      • 2011-12-05
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      • 1970-01-01
      • 2013-07-22
      • 1970-01-01
      • 2019-08-15
      相关资源
      最近更新 更多