如何仅计算R中特定行的列值

时间:2018-11-14 13:42:57

标签: r

我只计算“ A到D”列的total_buy /总销售量…… 它不应包含“ E到H”列

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试避免插入图片并检查解决方法:

dummy<-data.frame(A=sample(c("buy","sell"),100,replace = T),
           B=sample(c("buy","sell"),100,replace = T),
           C=sample(c("buy","sell"),100,replace = T),
           D=sample(c("buy","sell"),100,replace = T),
           E=sample(c("buy","sell"),100,replace = T),
           G=sample(c("buy","sell"),100,replace = T))

head(dummy)

     A    B    C    D    E    G
1  buy  buy sell sell  buy  buy
2  buy  buy  buy  buy  buy  buy
3  buy sell  buy  buy sell  buy
4 sell  buy  buy sell  buy sell
5 sell sell sell sell sell sell
6 sell sell  buy sell sell sell

现在将sapply应用于1:4(即从A到D)的选定列上的函数

sapply(dummy[1:4], function(x) table((x)))

输出:

      A  B  C  D
buy  50 53 53 51
sell 50 47 47 49