我在R中有一个三维数组。我想使用count函数将其总结为一个三维矩阵。我该怎么办?
# input
scm_test <- array(0,c(5,5,2))
sender_test <- c(1,1,3,4,5)
reciever_test <- c(2,2,1,5,2)
week_test <- c(1,1,2,1,2)
df <- as.data.frame(cbind(sender_test,reciever_test, week_test))
sender_1 <- df$sender_test
reciever_1 <- df$reciever_test
week_1 <- df$week_test
sender =df$sender
reciever=df$reciever
month =df$week_1
# the output should look like scm_test
scm_test[1,2,1] <- 2
scm_test[3,1,2] <- 1
scm_test[4,5,1] <- 1
scm_test[5,2,2] <- 1
scm_test
答案 0 :(得分:1)
我们可以这样进行:首先通过对“ df”的所有列进行分组来获取计数,然后使用“ df”作为3D索引来分配新的计数“ val”
library(tidyverse)
val <- df %>%
group_by_all() %>%
mutate(n = n()) %>%
pull(n)
或者使用ave
中的base R
获取“ val”
val <- with(df, ave(seq_along(sender_test), sender_test,
reciever_test, week_test, FUN = length))
scm_test[as.matrix(df)] <- val
scm_test
#, , 1
# [,1] [,2] [,3] [,4] [,5]
#[1,] 0 2 0 0 0
#[2,] 0 0 0 0 0
#[3,] 0 0 0 0 0
#[4,] 0 0 0 0 1
#[5,] 0 0 0 0 0
#, , 2
# [,1] [,2] [,3] [,4] [,5]
#[1,] 0 0 0 0 0
#[2,] 0 0 0 0 0
#[3,] 1 0 0 0 0
#[4,] 0 0 0 0 0
#[5,] 0 1 0 0 0
或使用count
dfN <- df %>%
count(!!! rlang::syms(names(.)))
replace(scm_test, as.matrix(dfN[names(df)]), dfN$n)
scm_test <- array(0,c(5,5,2))
答案 1 :(得分:0)
我通常尝试避免for循环,但是在这种情况下,这感觉像是最简单的解决方案:
for(i in 1:nrow(df)) {
scm_test[df[i,1],df[i,2],df[i,3]]<-scm_test[df[i,1],df[i,2],df[i,3]]+1
}