这是相当明星的前进,但我似乎无法在R中做到这一点,主要是因为我对语言的严重限制
所以我有一张表,它是一种奇点矩阵: 它的形式为:
rownames C1 C2 C3 C4
R1 0 1 0 1
R2 0 1 1 0
R3 1 0 1 0
R4 0 0 0 0
所以我想用一种完美的方式来绘制这个,我找到的一种方法是,如果我改变矩阵以在数据中显示rownames本身,
所以在表格中有' 1',我想用相应的rowname替换它
所以我想做的是:
rownames C1 C2 C3 C4
R1 0 R1 0 R1
R2 0 R2 R2 0
R3 R3 0 R3 0
R4 0 0 0 0
我意识到这很简单,但我发现R语言很难理解。
提前致谢
答案 0 :(得分:2)
这是一个可能的矢量化解决方案
indx <- which(df == 1, arr.ind = TRUE)
df[indx[order(indx[, 1]), ]] <- rep(row.names(df), rowSums(df))
# C1 C2 C3 C4
# R1 0 R1 0 R1
# R2 0 R2 R2 0
# R3 R3 0 R3 0
# R4 0 0 0 0
数据强>
df <- structure(list(C1 = c(0L, 0L, 1L, 0L), C2 = c(1L, 1L, 0L, 0L),
C3 = c(0L, 1L, 1L, 0L), C4 = c(1L, 0L, 0L, 0L)), .Names = c("C1",
"C2", "C3", "C4"), class = "data.frame", row.names = c("R1",
"R2", "R3", "R4"))
答案 1 :(得分:1)
如果rownames
是一列,您可以执行以下操作:
t(apply(d,1,function(rw) {rw[rw==1] <- rw[1]; rw}))
将逐行扫描数据框,并将1
替换为第一列中的相应值。
d
是初始数据集:
d <- structure(list(rownames = structure(1:4, .Label = c("R1", "R2",
"R3", "R4"), class = "factor"), C1 = c(0L, 0L, 3L, 0L), C2 = c(1L,
2L, 0L, 0L), C3 = c(0L, 2L, 3L, 0L), C4 = c(1L, 0L, 0L, 0L)), .Names = c("rownames",
"C1", "C2", "C3", "C4"), row.names = c(NA, -4L), class = "data.frame")
答案 2 :(得分:1)
df<-structure(list(C1 = c(0L, 0L, 1L, 0L), C2 = c(1L, 1L, 0L, 0L),
C3 = c(0L, 1L, 1L, 0L), C4 = c(1L, 0L, 0L, 0L)), .Names = c("C1",
"C2", "C3", "C4"), row.names = c("R1", "R2", "R3", "R4"), class = "data.frame")
for(i in 1:ncol(df)){
df[df[,i]==1,i]<-row.names(df)[which(df[,i]==1)]
}
> df
C1 C2 C3 C4
R1 0 R1 0 R1
R2 0 R2 R2 0
R3 R3 0 R3 0
R4 0 0 0 0
>
答案 3 :(得分:0)
也许你也可以尝试(使用@David Arenburg的数据)
df[!!df] <- rownames(df)[row(df)*!!df]
df
# C1 C2 C3 C4
#R1 0 R1 0 R1
#R2 0 R2 R2 0
#R3 R3 0 R3 0
#R4 0 0 0 0