如何根据第一列值将列从一个矩阵传输到另一个矩阵

时间:2014-09-24 08:44:03

标签: r

我有以下矩阵:

1 a d
2 s c
4 d 0 
7 f t

我希望得到以下内容:

1 a d
2 s c
3 0 0
4 d 0
5 0 0
6 0 0
7 f t

此外,我希望以一种我不必指定每一列的方式来完成......

谢谢你, ģ

2 个答案:

答案 0 :(得分:1)

如果datdata.frame(最好在data.frame中存储mixed类列而不是矩阵中

dat2 <- as.data.frame(matrix(0, ncol=ncol(dat), nrow=max(dat$V1)))
dat2$V1 <- 1:nrow(dat2)
dat2[dat2$V1 %in% dat$V1,-1] <- unlist(dat[,-1])
dat2
#  V1 V2 V3
#1  1  a  d
#2  2  s  c
#3  3  0  0
#4  4  d  0
#5  5  0  0
#6  6  0  0
#7  7  f  t

或者你可以做到

dat1 <- transform(dat[rep(1:nrow(dat),c(1,diff(dat$V1))),], V1=seq_along(V1))
dat1[duplicated(dat1[,-1], fromLast=TRUE),-1] <- 0

数据

dat <- structure(list(V1 = c(1L, 2L, 4L, 7L), V2 = c("a", "s", "d", 
"f"), V3 = c("d", "c", "0", "t")), .Names = c("V1", "V2", "V3"
), class = "data.frame", row.names = c(NA, -4L))

答案 1 :(得分:1)

或使用merge

df2 <- merge(data.frame(V1 = seq_len(max(df[, 1]))), df, by = "V1", all.x = TRUE) 
df2[is.na(df2)] <- 0
#   V1 V2 V3
# 1  1  a  d
# 2  2  s  c
# 3  3  0  0
# 4  4  d  0
# 5  5  0  0
# 6  6  0  0
# 7  7  f  t

df

的位置
df <- structure(list(V1 = c(1L, 2L, 4L, 7L), V2 = c("a", "s", "d", 
"f"), V3 = c("d", "c", "0", "t")), .Names = c("V1", "V2", "V3"
), class = "data.frame", row.names = c(NA, -4L))