Random string selection in R

I have this data file

id <- c(1,1,1,2,2,3) name <- c("A","A","A","B","B","C") value <- c(7:12) df<- data.frame(id=id, name=name, value=value) df 

This function selects a random string from it:

 randomRows = function(df,n){ return(df[sample(nrow(df),n),]) } 

i.e.

 randomRows(df,1) 

But I want to randomly select one row for "name" (or for "id", which is the same) and merge this whole row into a new table, so in this case three rows. This should loop through a 2000-bit data array. Please show me how ?!

+6
source share
2 answers

I think you can do this with the plyr package:

 library("plyr") ddply(df,.(name),randomRows,1) 

which gives you for example:

  id name value 1 1 A 8 2 2 B 11 3 3 C 12 

Is this what you are looking for?

+2
source

Here is one way to do this in the R database.

 > df.split <- split(df, df$name) > df.sample <- lapply(df.split, randomRows, 1) > df.final <- do.call("rbind", df.sample) > df.final id name value A 1 A 7 B 2 B 11 C 3 C 12 
+2
source

Source: https://habr.com/ru/post/912381/


All Articles