Add the number in every row and take the sum

Viewed 115

Having a dataframe like this

data.frame(id = c(1,2), num = c("30, 4, -2,","10, 20"))

How is it possible to take the sum of every row from the column num, and include the minuse into the calculation? Example of expected output?

data.frame(id = c(1,2), sum = c(32, 30)
3 Answers

Using Base R you could do the following:

# data
df <- data.frame(id = c(1,2), num = c("30, 4, -2,","10, 20"))

# split by ",", convert to numeric and then sum
df[, 2] <- sapply(strsplit(as.character(df$num), ","), function(x){
  sum(as.numeric(x))
})

# result 
df
#   id num
# 1  1  32
# 2  2  30

If you can use packages, the tidy packages make this easy and use tidy data principals which are quick and easy once you get used to thinking this way.

library(tidyr)
library(dplyr)
df %>%
  # Convert the string of numbers to a tidy dataframe
  # with one number per row with the id column for grouping
  separate_rows(num,sep = ",") %>%
  # Convert the text to a number so we can sum
  mutate(num = as.numeric(num)) %>%
  # Perform the calculation for each id
  group_by(id) %>%
  # Sum the number
  summarise(sum = sum(num,na.rm = TRUE)) %>%
  # Ungroup for further use of the data
  ungroup()
# A tibble: 2 x 2
#      id   sum
#   <dbl> <dbl>
# 1     1    32
# 2     2    30
library(stringr)

df <- data.frame(id = c(1,2), num = c("30, 4, -2","10, 20"))

df$sum <- NA

for (i in 1:nrow(df)) {

  temp <- as.character(df[i,2])

  n_num <- str_count(temp, '[0-9.]+')

  total <- 0

  for (j in 1:n_num) {

    digit <- strsplit(temp, ',')[[1]][j]

    total <- total + as.numeric(digit)

    temp <- sub(digit, '', temp)

  }

  df[i, 'sum'] <- total

}

print(df)

  id       num sum
1  1 30, 4, -2  32
2  2    10, 20  30
Related