Gilrob
Gilrob

Reputation: 95

Pivot wider to new column based on condition R

I have a dataset associating a single application number with a series of different applicants from different countries. I have a column with each applicant's country of origin as the possible value. I want to condense everything down to 2 columns:

column 1 = count of applicants within USA

column 2 = count of applicants Outside USA

I guessed I would need to use an ifelse but I haven't managed to get anything to work so far, can someone please help?

Thanks!!

ps. If anyone knows how I could do this and produce a list of the countries outside USA like @sotos has done here Pivot wider returning 1 column? that would be even better, but that's just bonus :)

Upvotes: 0

Views: 604

Answers (1)

Jon Spring
Jon Spring

Reputation: 66870

Like so?

df <- data.frame(app_num = c(1,1,1,2,2),
                 country = c(LETTERS[c(1:4,1)])) 

library(tidyverse)
df %>%
  count(A = if_else(country == "A", "USA", "Other")) %>%
  pivot_wider(names_from = A, values_from = n)

Upvotes: 0

Related Questions