Count occurrence of events traversing columns of a dataframe through a for loop in R

Asked

Viewed 62 times

0

Hello, I am using the table() function of R to count the repeated notes in each semester column (sem1, sem2,sem3...) of my file. It’s working properly, but I’d like to do it through a loop for and if possible directly on another dataframe, without the need to open an array for it and convert it to the end again.

If anyone can help, thank you.

datafile <- read.table("notasalunos.csv", stringsAsFactors = TRUE, sep = ";", header=TRUE)

matriz <- matrix(nrow=25,ncol=16)


matriz[,1] <- table(datafile$sem1)

matriz[,2] <- table(datafile$sem2)

matriz[,3] <- table(datafile$sem3)

matriz[,4] <- table(datafile$sem4)

matriz[,5] <- table(datafile$sem5)

matriz[,6] <- table(datafile$sem6)

matriz[,7] <- table(datafile$sem7)

matriz[,8] <- table(datafile$sem8)

matriz[,9] <- table(datafile$sem9)

matriz[,10] <- table(datafile$sem10)

matriz[,11] <- table(datafile$sem11)

matriz[,12] <- table(datafile$sem12)

matriz[,13] <- table(datafile$sem13)

matriz[,14] <- table(datafile$sem14)

matriz[,15] <- table(datafile$sem15)

newdatafile <- as.data.frame(t(matriz))
  • 2

    Hello, you can edit the question and paste the result of dput(head(datafile, 40))? So you help whoever’s here to help you.

1 answer

1


You can try:

cols <- paste0("sem", 1:15)

as.data.frame(sapply(datafile[,cols], table))

the command sapply makes the table in each of the columns for you, ie the for.

  • Legal but in this case the instruction cols <- paste0(c("without", 1:15)) does not generate sem1, sem2... but rather: sem, 1, 2, 3.... Do you have any idea how to fix it?

  • fixed. was without PC to test

  • Perfect! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.