[英]Fill missing values in a matrix with values from different rows in that matrix in R
[英]Fill a matrix with a value from another matrix in R
初始矩陣如下所示:
1 A 1
1 B 1
1 C 1
2 A 1
3 A 1
3 C 1
有必要記住:
A B C
1 1 1 1
2 1 0 0
3 1 0 1
我正在使用如下代碼:
for (i in 1:length(t_data$cid)) {
t_cid <- t_data$cid[i]
t_val <- t_data$eventAction[i]
df_events[grep(t_cid, df_events$cid),grep(paste0("^",t_val,"$"), colnames(df_events))] <- 1
print(i)
}
但是我們談論的是第一個矩陣中有超過一百萬行,第二個矩陣中有一百列。 5 分鍾內大約 10k 行,太慢了。 請幫忙。
我認為xtabs
會有所幫助
> as.data.frame.matrix(xtabs(V3 ~ ., df))
A B C
1 1 1 1
2 1 0 0
3 1 0 1
數據
> dput(df)
structure(list(V1 = c(1L, 1L, 1L, 2L, 3L, 3L), V2 = c("A", "B",
"C", "A", "A", "C"), V3 = c(1L, 1L, 1L, 1L, 1L, 1L)), class = "data.frame", row.names = c(NA,
-6L))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.