dimanche 7 juin 2020

condition statement in apply function not work correctly in R

I have a dataframe like this:

library(dplyr)
id <- runif(1000,1000,3000) %>% round() %>% as.character()
freq <- rep(1:50,20)
data <- data.frame(id,freq)
GetID <- function(a){
  if (a[2]==1) newid <- a[1] else newid <- paste(a[1],1:a[2],sep = "-");
  return(newid)}
idlist <- data %>% apply(., 1, GetID)
idlist2 <- unlist(idlist) %>% as.data.frame()

I wanted to get a new ID vector. If the freq equals 1, the new ID equals the old one. If the freq is larger than 1, the new ID is the old id combined with its order. However, it seems the if statement didn't work correctly. All of new id had order number.

Aucun commentaire:

Enregistrer un commentaire