KT_1
KT_1

Reputation: 8474

Populating a dataframe using an if statement

For a sample dataframe:

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

I want to assign 'a' to a new 'a_col' column which is added to the database in the 'uk' row.

I want to assign each country's 'a_col' column in turn. I have got this line of code to work using ifelse:

df$a_col <- ifelse(df$country=='uk', a, NA)

However, I don't want an 'else' as I want to add each country's value in turn. Why can't I get this 'if' statement to work?

df$a_col <- if(df$country=='uk', a)

I know if has something to do with the length of 'df$country=='uk'', but can I rectify this?

Any ideas would be grateful.

Upvotes: 0

Views: 111

Answers (2)

mtoto
mtoto

Reputation: 24178

You can avoid the ifelse statement if you populate only a subset of your new column:

df$a_col[df$country == "uk"] <- a
> df
#  country   N a_col
#1      uk 100     4
#2      fr  80    NA
#3      it  95    NA

Upvotes: 1

MasterJedi
MasterJedi

Reputation: 1638

What about this:
cbind(df, data.frame(model.matrix(~ -1 + country, data = df)))

Upvotes: 0

Related Questions