简体   繁体   中英

How to Create an ID column in R and Randomly Assign data to groups

I have a dataset called "SPIP5" in R that is just currently a list of 50 observations. Currently looking like:

Observations
20.46
3.08
2.07
18.2

I created a ID column by using;

data.frame <- tibble:: rowid_to_column(SPIP5, "ID")

This worked however, I don't know how to randomly assign the 50 observations between two groups and keep The IDs. Does any one have any recommendations.

I'm hoping for the dataset to look like this;

ID Observation Group (A or B
1 20.6 A
2 2.07 B
3 18.2 B
... --- ---

sample will help you assign two groups randomly.

SPIP5 <- tibble:: rowid_to_column(SPIP5, "ID")
SPIP5$Group <- sample(c('A', 'B'), nrow(SPIP5), replace = TRUE)

dplyr version

library(dplyr)

SPIP5 %>% mutate(ID = row_number(), Group = sample(LETTERS[1:2], as.numeric(n()), replace = T))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM