Do a function that returns the average of the notes that person participates in R

Asked

Viewed 32 times

1

inserir a descrição da imagem aqui

How can I do a function that returns the average of MARIA notes

my code is like this:

PESSOA = (got$Personagens)
NOTAS = (got$Nota)

medianotas = function(tabelaNotas, tabelaPessoas, nome)
    Nota = c()
    arrayPessoas = c()

    for(i in 1:length(tabelaPessoas))
        arrayPessoas = c(arrayPessoas, PESSOA[i])
        arraySplit = c(unlist(strsplit(as.character(arrayPessoas,","))))


    return()

resposta = medianotas(got$Nota, got$Personagens, "MARIA")
print(resposta)

After each name has a comma

Dice.

Notas <- c(9, 8.1, 7)
Personagens <- c("João,Maria,Eduardo", 
             "Pedro,Carlos,Maria", 
             "Bruno,Patrícia,Joana")
got <- data.frame(Notas, Personagens)

1 answer

1

The following function does what the question asks. No cycles are required for, is all vectored. The main job is to split the column "Personagens" by commas and then use function lengths to obtain the lengths of each vector corresponding to the already separated names.

medianota <- function(DF, Pessoa){
  s <- strsplit(as.character(DF[["Personagens"]]), ',')
  dftmp <- data.frame(Personagens = trimws(unlist(s)), 
                      Notas = rep(DF[["Notas"]], lengths(s)))
  inx <- tolower(dftmp[["Personagens"]]) == tolower(Pessoa)
  NotasPessoa <- dftmp[["Notas"]][inx]
  mean(NotasPessoa)
}

medianota(got, "Maria")
#[1] 8.55

Dice.

Notas <- c(9, 8.1, 7)
Personagens <- c("João, Maria, Eduardo", 
             "Pedro, Carlos, Maria", 
             "Bruno, Patrícia, Joana")
got <- data.frame(Notas, Personagens)

Browser other questions tagged

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