0

For some reason I cannot use a custom function with ddply. It returns exactly the same data frame.

Basically, I want not to count the number of duplicates of id, but actually create a variable that says if it is the first, second, or third instance of that repetition of id. Wrote a function for that , create_guide, which works; but does not work with the id groups.

df<-data.frame(id=c(1,1,2,2,3,4))

create_guide <- function(dt) {

  guide <- rep(0,times=nrow(dt))

  for (i in 1:nrow(dt)) {
    guide[i] <- length(dt[1:i,1])
  }

  a <- cbind(guide,dt)

}

bi <- plyr::ddply(df,.(id),fun=create_guide)

What is happening? Thank you

5
  • 1
    Your function is using the variable i in the first expression without having defined it previously. What i is it using? Commented Mar 13, 2018 at 15:57
  • @KonradRudolph it should be a 0. it's just to store the results from the loop. thanks. does not solve the problem though... Commented Mar 13, 2018 at 16:00
  • This is a typo. it should be .fun=, not fun=. Commented Mar 13, 2018 at 16:06
  • thanks for saving me. spent 40min on it. thanks! Commented Mar 13, 2018 at 16:08
  • what is i in guide <- rep(i,times=nrow(dt)) Commented Mar 13, 2018 at 16:11

1 Answer 1

1

You misspelled the argument name: it’s .fun, not fun. You can also omit it:

bi <- ddply(df, .(id), .fun = create_guide)
# or
bi <- ddply(df, .(id), create_guide)

Furthermore, your function can be drastically simplified, since your loop body is merely a convoluted way of assigning consecutive numbers:

create_guide = function(dt) {
    cbind(guide = seq_len(nrow(dt)), dt)
}

(Incidentally, it took me a substantial amount of time to simplify the function down to this single line because I couldn’t understand what it was doing — that’s how complex the code was.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.