mercredi 6 avril 2016

R: Create matrix of values from other table

I have the following data frame, table5, made up of x and its frequency, produced from other data using counts:

  x freq
1 1    3
2 3   21
3 4   21
4 5 1345
5 7    1

which I would like to transfer - in a general fashion, i.e. for use with other values in original data frame - into the following data frame table5if:

      Frequency
3             21
4             21
5             1345
other         4

i.e. where the frequency of the numbers 3, 4 and 5 is transferred directly, and all other numbers are added together in other. My latest attempt is this:

k <- seq(1, nrow(table5), by=1)
    ifelse(table5$x[k] == 3, table5if[1] <- table5$freq[k],
          ifelse(table5$x[k] == 4, table5if[2] <- table5$freq[k],
                ifelse(table5$x[k] == 5, table5if[3] <- table5$freq[k], table5if[4] <- (table5if[4] + table5$freq[k])
                  )
            )
      )

This attempt, and other attempts using if(...){...} else {...} etc., have all yielded some form of warning or error (e.g. "number of items to replace..." and "number of dimensions..." and haven't produced any convincing results. I've looked through countless other questions for both errors/warnings and can't quite find what I'm looking for - there's a lot about vectorisation but I can't quite get my head around why that would be the issue. Can anyone please suggest a suitable option for this small task?

Many thanks in advance!

Aucun commentaire:

Enregistrer un commentaire