Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum two columns in R

Tags:

r

I feel a bit embarrassed as I am trying to add two columns in R to get the product.

I have tried

sum(col1,col2)

but this returns

Error in Summary.factor(c(49L, 48L, 47L, 46L, 46L, 45L, 45L, 44L, 43L,  : 
  sum not meaningful for factors

I thought this would very simple! both columns contain integers.

like image 823
brucezepplin Avatar asked Sep 25 '14 19:09

brucezepplin


People also ask

How do you find the sum of two columns in R?

We can calculate the sum of multiple columns by using rowSums() and c() Function. we simply have to pass the name of the columns.

How do I sum a column value in R?

Sum Function in R – sum() sum of a particular column of a dataframe. sum of a group can also calculated using sum() function in R by providing it inside the aggregate function. with sum() function we can also perform row wise sum using dplyr package and also column wise sum lets see an example of each.

How do I add two rows in R?

First of all, create a data frame. Then, using plus sign (+) to add two rows and store the addition in one of the rows. After that, remove the row that is not required by subsetting with single square brackets.


1 Answers

The sum function will add all numbers together to produce a single number, not a vector (well, at least not a vector of length greater than 1).

It looks as though at least one of your columns is a factor. You could convert them into numeric vectors by checking this

head(as.numeric(data$col1))  # make sure this gives you the right output

And if that looks right, do

data$col1 <- as.numeric(data$col1)
data$col2 <- as.numeric(data$col2)

You might have to convert them into characters first. In which case do

data$col1 <- as.numeric(as.character(data$col1))
data$col2 <- as.numeric(as.character(data$col2))

It's hard to tell which you should do without being able to see your data.

Once the columns are numeric, you just have to do

data$col3 <- data$col1 + data$col2
like image 137
blakeoft Avatar answered Sep 23 '22 15:09

blakeoft