从数据框内的对中填充值

时间:2016-03-30 02:14:37

标签: r

我的数据框看起来像这样(但是是285 x 12300),有一些分散的na:

     X5f65665a X8c267f9f X169df433 X5742e722 X148d530d X88febf48
F185 X5f65665a         0 X169df433         0 X148d530d X88febf48
F186 X5f65665a         0 X169df433         0 X148d530d         0
M187 X5f65665a X8c267f9f X169df433         0 X148d530d X88febf48
F188 0         X8c267f9f X169df433         0 X148d530d         0
M189 X5f65665a X8c267f9f X169df433         0 X148d530d X88febf48
F190 X5f65665a         0 X169df433         0 X148d530d X88febf48

在左边的rownames之后,列是成对的(cols 1& 2; 3& 4等)。我需要用该对中的伙伴值替换任何“0”。所以(1,2)应该变成X5f65665a而(4,1)应该变成X8c267f9f。

1 个答案:

答案 0 :(得分:1)

d1 <- read.table(text="
     X5f65665a X8c267f9f X169df433 X5742e722 X148d530d X88febf48
F185 X5f65665a         0 X169df433         0 X148d530d X88febf48
F186 X5f65665a         0 X169df433         0 X148d530d         0
M187 X5f65665a X8c267f9f X169df433         0 X148d530d X88febf48
F188 0         X8c267f9f X169df433         0 X148d530d         0
M189 X5f65665a X8c267f9f X169df433         0 X148d530d X88febf48
F190 X5f65665a         0 X169df433         0 X148d530d X88febf48", 
                 head=T, as.is=T, row.names=1)

d1.lst <- lapply(seq(1, ncol(d1), by=2), function(x){return(d1[, x:(x+1)])})
d1.lst.fil <- lapply(d1.lst, function(x){
  x[,1][x[,1]==0] <- x[,2][x[,1]==0]
  x[,2][x[,2]==0] <- x[,1][x[,2]==0]
  return(x)
})

d2 <- do.call(cbind, d1.lst.fil)
#      X5f65665a X8c267f9f X169df433 X5742e722 X148d530d X88febf48
# F185 X5f65665a X5f65665a X169df433 X169df433 X148d530d X88febf48
# F186 X5f65665a X5f65665a X169df433 X169df433 X148d530d X148d530d
# M187 X5f65665a X8c267f9f X169df433 X169df433 X148d530d X88febf48
# F188 X8c267f9f X8c267f9f X169df433 X169df433 X148d530d X148d530d
# M189 X5f65665a X8c267f9f X169df433 X169df433 X148d530d X88febf48
# F190 X5f65665a X5f65665a X169df433 X169df433 X148d530d X88febf48

更新(对于dnatheist):

问题是由&#34; NA&#34;引起的。请尝试以下脚本。它会离开&#34; NA&#34;不变。

d1.lst.fil <- lapply(d1.lst, function(x){
  x[,1][!is.na(x[,1]) & x[,1]=="0"] <- x[,2][!is.na(x[,1]) & x[,1]=="0"]
  x[,2][!is.na(x[,2]) & x[,2]=="0"] <- x[,1][!is.na(x[,2]) & x[,2]=="0"]
  return(x)
})