0

For a sample dataframe:

country = c("uk", "fr", "it") 
N = c(100, 80, 95)
df <- data.frame(country, N)

I wish to populate two extra columns (say 'a_col' and 'b_col') in my 'df' dataframe with values calculated from a previous command. For simplicity, values for the UK to populate the two columns (first row) mentioned above would be:

a <- 5.5
b <- 3.6

How would I add these values to the dataframe in the right row? (i.e. for the UK only, not the other countries). If it could be wrapped up in a function, I guess that would be the easiest - could I use 'sapply'?

KT_1
  • 8,194
  • 15
  • 56
  • 68
  • You can use `cbind(df, a_col=a, b_col=b)` or `transform` or `data.frame` or `within` etc. – akrun Feb 17 '16 at 17:21
  • 1
    `df$new_column <- some_value`? – nrussell Feb 17 '16 at 17:22
  • Thanks @akrun. I know how to add the same value for entire column, but not specifying the value with reference to a row in another column - i.e. the a and b values would just refer to the UK - I would then calculate another a and b with reference to values for 'FR' and then add these individually to the dataframe also - how would I do that? – KT_1 Feb 18 '16 at 12:33
  • Thanks @nrussell - but I wanted to instead add these values just for the UK row (sorry if I wasn't clear... I have edited my answer). I will then have different values for the other countries. – KT_1 Feb 18 '16 at 12:57
  • You could use `ifelse` i.e. `ifelse(df$country=='uk', a, NA)` – akrun Feb 18 '16 at 17:14
  • Thanks @akrun. If I didn't want to add the else (since I will be repeating the same process with lots of countries), why doesn't df$a_col <- if(df$country=='uk', a) work or this df$a_col <- if(df$country=='uk') {a} ? – KT_1 Feb 19 '16 at 12:09
  • It is because `if` is not vectorized. If the logical index is just a single value, it should work. – akrun Feb 19 '16 at 12:11
  • Thanks @akrun, but I still don't understand. In the above example, the logical index does refer to a single value (uk) but I get the warning message Error: unexpected ',' in "df$a_col <- if(df$country=='uk'," How can I get this to work? – KT_1 Feb 19 '16 at 14:12
  • @KT_1 If you look a the `df$country=='uk'` it is a vector of length >1. THe `if/else` works when the length is 1. – akrun Feb 19 '16 at 14:16
  • Ok, I understand that. But (1) why does ifelse work in these circumstances? df$a_col <- ifelse(df$country=='uk', a, NA) ... and (2)how would I get my if command to reference just the UK, therefore of length one? – KT_1 Feb 19 '16 at 15:32

0 Answers0