-3

I want to add a column in r to calculate the difference of scores for every equal characters in the same column (e.g:names)

I tried to group the data using group_by function in dplyr but it didn't work.

ashwin agrawal
  • 1,603
  • 8
  • 16
Hus Has
  • 11
  • 1
  • 2
    Please show a small reproducible example and expected output based on that example – akrun Oct 23 '19 at 20:35
  • 2
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. What does "didn't work" mean exactly? Did you get an error message? – MrFlick Oct 23 '19 at 20:36
  • For e.g: col 1: James, Andrew, James, Sonya, Catherine, Sonya col2:83,84,87,40,50,55......for every same name I want score difference – Hus Has Oct 23 '19 at 20:40
  • @HusHas Please don't include critical data/code in comments; instead edit your question. It's also best to include your expected output for the sample data you give. That often helps us understand what you're trying to do. – Maurits Evers Oct 23 '19 at 21:42

1 Answers1

0

Something like this?

library(dplyr)
df %>% group_by(name) %>% mutate(score_diff = c(0, diff(score)))
## A tibble: 6 x 3
## Groups:   name [4]
#  name      score score_diff
#  <fct>     <dbl>      <dbl>
#1 James        83          0
#2 Andrew       84          0
#3 James        87          4
#4 Sonya        40          0
#5 Catherine    50          0
#6 Sonya        55         15

Sample data

df <- data.frame(
    name = c("James", "Andrew", "James", "Sonya", "Catherine", "Sonya"),
    score = c(83,84,87,40,50,55))
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68