Random row selection in R

后端 未结 2 1350
臣服心动
臣服心动 2020-12-20 19:47

I have this dataframe

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, valu         


        
相关标签:
2条回答
  • 2020-12-20 20:01

    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?

    0 讨论(0)
  • 2020-12-20 20:05

    Here's one way of doing it in base R.

    > 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
    
    0 讨论(0)
提交回复
热议问题