Randomly sample a percentage of rows within a data frame
问题 Related to this question. gender <- c("F", "M", "M", "F", "F", "M", "F", "F") age <- c(23, 25, 27, 29, 31, 33, 35, 37) mydf <- data.frame(gender, age) mydf[ sample( which(mydf$gender=='F'), 3 ), ] Instead of selecting a number of rows (3 in above case), how can I randomly select 20% of rows with "F"? So of the five rows with "F", how do I randomly sample 20% of those rows. 回答1: How about this: mydf[ sample( which(mydf$gender=='F'), round(0.2*length(which(mydf$gender=='F')))), ] Where 0.2 is