nzei s
nzei s

Reputation: 5

how can i use for loop to simplify this coding?

A$`Type B`=c(17 2, 9, 0, 5, 8)
A$`Type C`=c(1, 0, 1, 1, 0, 1)

p1=sum(A$`Type B`==1 & A$`Type C` ==0)
p1*1
p11=sum(A$`Type B`==1 & A$`Type C` ==1)
p11*1

p2=sum(A$`Type B`==2 & A$`Type C` ==0)
p2*2
p21=sum(A$`Type B`==2 & A$`Type C` ==1)
p21*2

p3=sum(A$`Type B`==3 & A$`Type C` ==0)
p3*3
p31=sum(A$`Type B`==3 & A$`Type C` ==1)
p31*3
...

how can i use for loop to simplify this coding? for (i in 1:5) A$Type B== [i] then p[i]1*[i]

Upvotes: 0

Views: 65

Answers (3)

akrun
akrun

Reputation: 887088

We can use data.table

library(data.table)
setDT(A)[, .(n = .N), .(`Type B`, `Type C`)][, n := n * `Type B`][]

Upvotes: 0

Anoushiravan R
Anoushiravan R

Reputation: 21908

If you would like to use a for loop to count the frequencies you can use the following solution:

# First we create an empty frequency matrix. Then we set the rownames and colnames to 
# the values they could take

result <- matrix(nrow = 3, ncol = 2)
dimnames(result) <- list(c(1, 2, 3), c(0, 1))

# Then we populate the empty frequency matrix by the number of occurrence of 
# each combination

for(i in as.numeric(rownames(result))) {
  for(j in as.numeric(colnames(result))) {
    result[i, j + 1] <- sum(A$`Type B` == i & A$`Type C` == j) * i
  }
}

result

  0 1
1 3 1
2 2 2
3 0 3

I have created a sample data to test the for loop.

A <- data.frame(`Type B` = c(1, 1, 2, 1, 2, 3, 1), 
                `Type C` = c(0, 0, 1, 0, 0, 1, 1), check.names = FALSE)  

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388972

Using dplyr, you can try :

library(dplyr)
res <- A %>%  count(`Type B`, `Type C`) %>% mutate(n = n * `Type B`)

Upvotes: 1

Related Questions