1

I would like help with a simple operation in a data frame. The data frame contains several variables corresponding to countries that are represented with a three letter coding. I would like to add or subtract values from these variables of specific countries.

There is a similar question asked here. In that case, however, the values are strings.

As an example, say I have the following data frame:

set.seed(10)

a <- data.frame(country = rep(c("aaa" , "bbb" , "ccc") , times = 3) ,
                year = rep(c(1990 , 1991 , 1992), each = 3) ,
                c = sample(9))

giving:

  country year c
1     aaa 1990 9
2     bbb 1990 2
3     ccc 1990 4
4     aaa 1991 6
5     bbb 1991 3
6     ccc 1991 7
7     aaa 1992 5
8     bbb 1992 1
9     ccc 1992 8

For example, I would like to add 5 to every country corresponding to "aaa", giving:

   country year  c
1     aaa 1990 14
2     bbb 1990  2
3     ccc 1990  4
4     aaa 1991 11
5     bbb 1991  3
6     ccc 1991  7
7     aaa 1992 10
8     bbb 1992  1
9     ccc 1992  8

Is there an efficient to code to do this? I appreciate any help.

1 Answer 1

1

Here is a two step base R way.

i <- df$country == "aaa"
df$c[i] <- df$c[i] + 5

A one-liner would be

df$c[df$country == "aaa"] <- df$c[df$country == "aaa"] + 5

Edit

If column country has missing values, NA's, then it's safer to index with

i <- which(df$country == "aaa")

or with the equivalent one-liner.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.