R根据变量的百分比

R根据变量的百分比,r,dataframe,percentage,R,Dataframe,Percentage,我有一个数据帧数据,我已经用dcast函数重塑了它。 现在,我想为每一个中心的值包括体重指数为3的人的百分比。例如,在A列旁边,我想要一列Aperc=c(50,33.33,20) 这是一张支票 我怎样才能在R中做到这一点 > library(reshape2) > data =data.frame("centre"=LETTERS[sample(1:10,size=100,replace=T)], "bmi"=sample(1:3,100, replace=T)) > head

我有一个数据帧数据,我已经用dcast函数重塑了它。 现在,我想为每一个中心的值包括体重指数为3的人的百分比。例如,在A列旁边,我想要一列Aperc=c(50,33.33,20) 这是一张支票

我怎样才能在R中做到这一点

> library(reshape2)
> data =data.frame("centre"=LETTERS[sample(1:10,size=100,replace=T)], "bmi"=sample(1:3,100, replace=T))
> head(data)
  centre bmi
1      F   2
2      A   1
3      E   3
4      I   1
5      E   1
6      A   1
> d_edu = dcast(data,bmi~centre)
Using bmi as value column: use value.var to override.
Aggregation function missing: defaulting to length
> d_edu
  bmi A B C D E F G H I J
1   1 5 1 2 6 3 5 3 2 4 0
2   2 3 0 1 2 4 8 2 6 6 3
3   3 2 2 2 3 4 6 3 5 5 2
>  
尝试:


d_edu1您可以使用for循环在列中填充以下内容

 d_edu[,toString(data[i,1]) ]/sum(d_edu[,toString(data[i,1]) ])

现在您已经将BMI值组织成了行,
prop.table
margin
的列设置为2,经过一点格式化和乘法后应该会成功(我在第一次阅读时不理解您希望通过按列单独执行此操作)我认为你的例子是错误的,因为中间的百分比值应该是30

 (props_d_edu <- 100*round(prop.table(as.matrix(d_edu[-1]), 2),2) )
 #    --- different than yours since set.seed() was not called ---------
       A  B  C  D  E  F  G  H  I  J
[1,] 43 12 25 50 45 25 33 62 25 43
[2,] 14 50 42 12 36 50 40 12 44 14
[3,] 43 38 33 38 18 25 27 25 31 43
试一试


这很接近我想要的,但是V列上的值总和不是100'>适用的(X=d_edu1,MARGIN=2,FUN=sum)我只是编辑了行d_edu1[,seq(3,ncol(d_edu1),by=2)]d_edu2[c(“bmi”,sort(names(d_edu2)[-1])]。#给出了重复的d_edu2[c(1,order(names(d_edu2)[-1])+1]
 d_edu[,toString(data[i,1]) ]/sum(d_edu[,toString(data[i,1]) ])
 (props_d_edu <- 100*round(prop.table(as.matrix(d_edu[-1]), 2),2) )
 #    --- different than yours since set.seed() was not called ---------
       A  B  C  D  E  F  G  H  I  J
[1,] 43 12 25 50 45 25 33 62 25 43
[2,] 14 50 42 12 36 50 40 12 44 14
[3,] 43 38 33 38 18 25 27 25 31 43
d_edu2 <- cbind(d_edu, props_d_edu)
d_edu2 <- d_edu2[ c("bmi", sort(names(d_edu2)[-1])) ]
d_edu2
  bmi A Aperc B Bperc C Cperc D Dperc E Eperc F Fperc G Gperc H Hperc I Iperc J Jperc
1   1 3    43 1    12 3    25 4    50 5    45 2    25 5    33 5    62 4    25 3    43
2   2 1    14 4    50 5    42 1    12 4    36 4    50 6    40 1    12 7    44 1    14
3   3 3    43 3    38 4    33 3    38 2    18 2    25 4    27 2    25 5    31 3    43
> 
 d_edu$Aperc <- d_edu$A/sum(d_edu$A)
 d_edu$Bperc <- d_edu$B/sum(d_edu$B)
 d_edu = d_edu[c( "bmi", "A",  "Aperc", "B", "Bperc", ..............)]