在R

时间:2018-11-09 19:30:11

标签: r dataframe matrix

R中是否有一种方法可以将矩阵/数据帧每一行中的值替换为该行中的特定值?

例如,我有以下矩阵:

df<-cbind(c("A","C","G","T"),c("T","G","C","A"),c(0,1,0,1),c(1,0,1,0),c(0,1,0,1))

df
#     [,1] [,2] [,3] [,4] [,5]
#[1,] "A"  "T"  "0"  "1"  "0"
#[2,] "C"  "G"  "1"  "0"  "1"
#[3,] "G"  "C"  "0"  "1"  "0"
#[4,] "T"  "A"  "1"  "0"  "1"

并且我想用该行第一列中的相应字母替换每一行中的零,以便新矩阵看起来像这样:

newdf
#     [,1] [,2] [,3] [,4] [,5]
#[1,] "A"  "T"  "A"  "1"  "A"
#[2,] "C"  "G"  "1"  "C"  "1"
#[3,] "G"  "C"  "G"  "1"  "G"
#[4,] "T"  "A"  "1"  "T"  "1"

我能获得的最接近的命令是以下命令,但它不会用第1列中的正确值替换零。

df[df==0]<-NA
df[, 3:ncol(df)][is.na(df[, 3:ncol(df)])] <- df[,1]

1 个答案:

答案 0 :(得分:0)

我们可以复制第一列以使长度相等,然后根据逻辑矩阵进行分配。它将子集与rhs中相同长度的元素

i1 <- df == 0
newdf <- df
newdf[i1] <- df[,1][row(df)][i1]
newdf
     [,1] [,2] [,3] [,4] [,5]
#[1,] "A"  "T"  "A"  "1"  "A" 
#[2,] "C"  "G"  "1"  "C"  "1" 
#[3,] "G"  "C"  "G"  "1"  "G" 
#[4,] "T"  "A"  "1"  "T"  "1"