如何在R中将矢量分成小组?

时间:2013-03-21 11:13:31

标签: r

x<-rnorm(5000,5,3)

如何将x拆分为500组,每组中有10个数字?

2 个答案:

答案 0 :(得分:4)

回答#1:

x<-rnorm(5000,5,3)
y<-matrix(nr=500,nc=10)
y[]<-x

回答#2: 跳过第一步,直接创建矩阵。

y<-matrix(rnorm(5000,5,3),nr=500,nc=10)

答案 1 :(得分:0)

你在寻找这样的东西:

# create a vector of group labels

group <- rep(sample(1:500,replace=F,size=500),10)
group.name <- paste("group",as.character(group),sep=" ")

# create a dataframe of groups and corresponding values
df <- data.frame(group=group.name,value=rnorm(5000,5,3))

# check the dataframe
str(df)
'data.frame':   5000 obs. of  2 variables:
 $ group: Factor w/ 500 levels "group 1","group 10",..: 271 115 404 252 138 243 375 308 434 16 ...
 $ value: num  8.55 10.14 3.71 8.79 4.17 ...

head(df)
      group     value
1 group 342  8.547406
2 group 201 10.135465
3 group 462  3.713305
4 group 325  8.786934
5 group 222  4.171373
6 group 317  3.478123