添加数据框的所有列

时间:2016-04-04 16:00:18

标签: r dataframe

我的问题很简单,但我被困了

我有一个大的csv datset,如下所示

Fruit   Apples Oranges Peaches
A          1     2       2
B          1     2       1
C          1     1       1

我需要的只是一列,总数如

Fruit  
  A      5         4    3

3 个答案:

答案 0 :(得分:0)

So you want another column that is essentially the sum of apples, peaches and oranges? I think this should work.

#take sum by row
x=Fruit$Apples + Fruit$Oranges +Fruit$Peaches
#create the column named x inside the data frame
dat[,'x'] =x

答案 1 :(得分:0)

Perhaps you are looking for something like aggregate, which will sum the values of Apples, Oranges, and Peaches by the category Fruit

    set.seed(100)
    mydata = data.frame(Fruit = rep(c("A", "B", "C"),  5), 
                Apples = rpois(15, 3), 
                Oranges = rpois(15, 3), 
                Peaches = rpois(15, 3))
    aggregate(cbind(Apples, Oranges, Peaches) ~ Fruit, mydata, sum)

which will output one row for each category of Fruit along with the totals:

     Fruit Apples Oranges Peaches
    1     A     10      17      15
    2     B     12      13      20
    3     C     18      15      23

答案 2 :(得分:0)

We can use rowSums

df1$Sum <- rowSums(df1[-1])
df1$Sum
#[1] 5 4 3

Or use + with Reduce

Reduce(`+`, df1[-1])
#[1] 5 4 3