vendredi 19 juillet 2019

How to randomize a character string in a dataframe in R

I have a data frame with 2 columns, each of the class "character". One column is the identifier and the second column consists of letters that I want to randomize.

df <- data.frame(identifier=c("number1", "number2", "number3"), 
                 values=c("AGLRJMV", "KTKOXSOCOFMTMSOV", "GTSHH"))

df$identifier <- as.character(as.factor(df$identifier))
df$values <- as.character(as.factor(df$values))

I wasn't able to randomize the letters because R doesn't see them as individual characters but as one string. So when I try

sample(df[,2]) 

it doesn't randomize the letters.

I tried to split the second column into single columns for each letter but then I wasn't able to join the columns back again because the number of columns is not the same.

So, what I want to have in the end is the following:

identifier values 
number1    MVARJGL
number2    OTMCOFMKOSOVKTXS
number3    STHHG

Sorry that this might be an obvious question, but I just can't figure it out.. If the question was already answered somewhere else, I'm happy to be directed to that question.

Thanks everybody!




Aucun commentaire:

Enregistrer un commentaire