R百分比根据变量

时间:2014-06-12 13:12:23

标签: r dataframe percentage

我有一个数据帧数据,我已使用dcast函数重新整形。 现在我想为每个中心值包含这样的bmi3的人的百分比。所以例如在A列旁边我想要一个Aperc = c列(50,33.33,20) 这里是RE。

我怎么能在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
>  

4 个答案:

答案 0 :(得分:0)

尝试:

d_edu1 <- as.data.frame(matrix(nrow=nrow(d_edu),ncol=(ncol(d_edu)-1)*2+1))
d_edu1[,1] <- d_edu[,1]
d_edu1[,seq(2,ncol(d_edu1), by=2)] <- d_edu[,-1]
d_edu1[,seq(3,ncol(d_edu1), by=2)] <- 100*round(t(t(d_edu[,-1])/colSums(d_edu[,-1])),2)

colnames(d_edu1)[c(1,seq(2,ncol(d_edu1), by=2))] <- colnames(d_edu)

colSums(d_edu1[,seq(3,ncol(d_edu1), by=2)]) ##rounding 
# V3  V5  V7  V9 V11 V13 V15 V17 V19 V21 
# 100 100  99 101 100 101 100 100 100  99 

您可以通过以下方式更改新生成的变量的名称:

 colnames(d_edu1)[c(3,seq(2,ncol(d_edu1), by=2))] <- vector_of_names

答案 1 :(得分:0)

你可以使用for循环用这个

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

答案 2 :(得分:0)

现在您已将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

现在通过对非“bmi”列名称进行排序来交错值:

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
> 

答案 3 :(得分:0)

 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", ..............)]
相关问题