0

I have received a transaction log where I track students logging into a Learning Management System (LMS). I have already managed to spread the data into weeks. The resulting data.frame looked as follows:

UserID   31        32        33        34        35
user1    active    active    n/a       n/a       active
user2    n/a       n/a       active    active    n/a
user3    active    n/a       n/a       active    active

I need to insert or replace the column values based on the preceeding value into something like below:

UserID     31       32       33       34       35
user1      new      recur    drop     drop     recur
user2      n/a      n/a      new      recur    drop
user3      new      drop     drop     recur    recur

This is to show students login patterns which differentiate between new user logging for the first time, recurring users and users who did not log in for a particular week.

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Sazril
  • 1
  • 3
    Welcome to SO. Please have a read at [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to make [reproducible examples](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Also include expected output and code that you tried and failed. And format your question correctly. – Sotos Dec 07 '16 at 13:37

1 Answers1

0

The duplicated function can be used for this.

Perhaps a bit verbose like this but:

df <- data.frame(user1=c('n/a','active','n/a','active'),
                 user2=c('n/a','n/a','n/a','n/a'),
                 user3=c('active','n/a','active','n/a'),
                 user4=c('active','active','active','active'),
                 stringsAsFactors = FALSE)

recode_col <- function(col) {
  coldup <- duplicated(col)
  colna <- col=='n/a'
  col[!coldup&!colna] <- 'new'
  col[coldup&!colna] <- 'recur'
  col[colna] <- 'drop'
  first_nonna <- which(!colna)[1]
  if (is.na(first_nonna)) first_nonna <- length(col)+1
  col[1:first_nonna-1] <- 'n/a'
  col
}

lapply(df, recode_col)
mpjdem
  • 1,504
  • 9
  • 14