1

I have a dataframe bask.df as below.

     basko1 basko2 
1st       6      1 
2nd      12      1 
3rd       8      8 
4th       4      5 
5th       1      2 
6th       8      9 
7th       1      2 
8th       8      9 
9th      12     14 
10th     15     10 
11th      3      6 
12th      5      2 
13th      4      6 
14th      3      1 
15th      4      6 
16th      3      1 

I want to add a third column named total, which is the sum of the integers in basko1 and basko2 columns.

When I try in R as :

bask.df['total'] <- as.numeric(bask.df['basko1']) + as.numeric(bask.df['basko2']) , 

it gives me the error as

Error: (list) object cannot be coerced to type 'double'

Is bask.df[basko1] and bask.df[basko2], which are seemingly vectors, actually present as lists here ? Or I am doing anything else wrong ?

Sarang Manjrekar
  • 1,839
  • 5
  • 31
  • 61

1 Answers1

1

The error in the OP's code is because of applying as.numeric to a data.frame i.e. bask.df['basko1'] us still a data.frame with a single column. The as.numeric can be applied to vector or matrix

bask.df['total'] <- as.numeric(bask.df[,'basko1']) + as.numeric(bask.df[,'basko2'])

In the above code, we added , to make it vector or it can be done with [[ i.e. bask.df[['bask01']]

A compact approach would be

bask.df['total'] <- with(bask.df, bask.o1 + basko2)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 2
    I would use `[[` or `$` instead of relying on `[` to drop single-column dfs to vectors. This "feature" has tripped me up countless times when I wasn't expecting it. – Hong Ooi Mar 06 '17 at 10:49
  • 3
    Plus, `[[` and `$` mean it'll also work with those tybbly-thingies. – Hong Ooi Mar 06 '17 at 10:50