Ana Wilmer
Ana Wilmer

Reputation: 63

Ifelse statement in R: One value cannot equal another

I have a dataframe with two columns: df$user and df$type. The users are a list of different user names and the type category has two values: 'high_user' and 'small_user'

I want to create some code so that one user cannot be both types. For example if the user is high_user he cannot also be a small_user.

head(df$user)

[1] RompnStomp       Vladiman         Celticdreamer54  Crimea is Russia shrek1978third   annietattooface 

head(df$type)

"high_user" "high_user" "small_user" "high_user" "high_user" "small_user"

Any help would be greatly appreciated.

Upvotes: 1

Views: 62

Answers (2)

akrun
akrun

Reputation: 887193

An option with base R

df$new_type <- with(df, ave(type, User, FUN = function(x) x[1]))

data

df <- data.frame(User = c('a', 'b', 'a', 'c', 'c'), 
      type = c('high_user', 'high_user', 'small_user', 'small_user', 'high_user'))

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388992

One way would be to assign the first value of User to all the values of it's type.

df$new_type <- df$type[match(df$User, unique(df$User))]
df

#  User       type   new_type
#1    a  high_user  high_user
#2    b  high_user  high_user
#3    a small_user  high_user
#4    c small_user small_user
#5    c  high_user small_user

This can also be done using grouped operations.

library(dplyr)
df %>% group_by(User) %>% mutate(new_type = first(type))

data

df <- data.frame(User = c('a', 'b', 'a', 'c', 'c'), 
      type = c('high_user', 'high_user', 'small_user', 'small_user', 'high_user'))

Upvotes: 1

Related Questions