在R中生成一个向量并将其插入到堆叠框架中
我想堆叠一个框架,但我认为我没有使用正确的方法...
myframe
sex = F
q8
cars N U Y
1 35 31 10
2 34 23 7
3 132 109 35
4 38 36 14
5 7 5 2
, , sex = M
q8
cars N U Y
1 49 22 16
2 24 13 8
3 136 52 33
4 37 31 32
5 15 10 4
f = c(myframe[1:15])
m = c(myframe[16:30])
S <- stack(data.frame(f,m))
names(S)=c("num","gender")
group=c("1","1","1","2","2","2","3","3","3","4","4","4","5","5","5","6","6","6","1","1","1","2","2","2","3","3","3","4","4","4","5","5","5")
num=S$num
gender=S$gender
twoway.df=data.frame(num,group,gender)
twoway.df
1 1 35 f
2 1 31 f
3 1 10 f
4 2 24 f
5 2 13 f
....
你能帮我做得更好吗?
I want to stack a frame but I think I do not use the right way...
myframe
sex = F
q8
cars N U Y
1 35 31 10
2 34 23 7
3 132 109 35
4 38 36 14
5 7 5 2
, , sex = M
q8
cars N U Y
1 49 22 16
2 24 13 8
3 136 52 33
4 37 31 32
5 15 10 4
f = c(myframe[1:15])
m = c(myframe[16:30])
S <- stack(data.frame(f,m))
names(S)=c("num","gender")
group=c("1","1","1","2","2","2","3","3","3","4","4","4","5","5","5","6","6","6","1","1","1","2","2","2","3","3","3","4","4","4","5","5","5")
num=S$num
gender=S$gender
twoway.df=data.frame(num,group,gender)
twoway.df
1 1 35 f
2 1 31 f
3 1 10 f
4 2 24 f
5 2 13 f
....
could you help me do it better ?
要将表格转换为 data.frame,基本函数
as.data.frame.table
应该可以工作。然而,我会这样做:
获取包含所有变量的 data.frame 。如果您只想将
q8
和sex
作为 data.frame 中的因素,请改用melt(myframe)[,-1]
。请参阅
help(melt.array)
了解更多信息。To transform a table into a data.frame, the base function
as.data.frame.table
should work.Here is, however, how I would do:
for getting a data.frame with all variables. Should you only want to keep
q8
andsex
as factors in your data.frame, usemelt(myframe)[,-1]
instead.See
help(melt.array)
for more information.