[英]Ifelse statement in R: One value cannot equal another
I have a dataframe with two columns: df$user
and df$type
.我有一个 dataframe 有两列:
df$user
和df$type
。 The users are a list of different user names and the type category has two values: 'high_user'
and 'small_user'
用户是不同用户名的列表,类型类别有两个值:
'high_user'
和'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
.例如,如果
user
是high_user
他不能同时是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.任何帮助将不胜感激。
One way would be to assign the first value of User
to all the values of it's type
.一种方法是将
User
的第一个值分配给它的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'))
An option with base R
base R
的选项
df$new_type <- with(df, ave(type, User, FUN = function(x) x[1]))
df <- data.frame(User = c('a', 'b', 'a', 'c', 'c'),
type = c('high_user', 'high_user', 'small_user', 'small_user', 'high_user'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.