Dataframe 如果满足条件,则重命名特定列中某行的某些值
如果某行的某个值符合某个if语句,如何重命名该列中的某个值 例如:Dataframe 如果满足条件,则重命名特定列中某行的某些值,dataframe,Dataframe,如果某行的某个值符合某个if语句,如何重命名该列中的某个值 例如: Date Type C1 2000 none 3 2000 love 4 2000 none 6 2000 none 2 2000 bad 8 所以我想把我列类型中的“love”和“bad”重命名为“xxx” 有什么好办法吗 谢谢:)首先,确保它不是一个因素,然后重命名: df$Type = as.char
Date Type C1
2000 none 3
2000 love 4
2000 none 6
2000 none 2
2000 bad 8
所以我想把我列类型中的“love”和“bad”重命名为“xxx”
有什么好办法吗
谢谢:)首先,确保它不是一个因素,然后重命名:
df$Type = as.character(df$Type)
df$Type[df$Type %in% c("love", "bad")] = "xxx"
如果数据是因子,则需要重命名因子级别。最简单的方法是使用
forcats
包中的fct\u recode()
。如果它是一个字符向量,ifelse
如果更改的数量很小,则效果很好。如果它很大,dplyr
包中的case_
运行良好
library(forcats)
library(dplyr)
df <- within(df, { # if you use `dplyr`, you can replace this with mutate. You'd also need to change `<-` to `=` and add `,` at the end of each line.
Type_fct1 <- fct_recode(Type, xxx = "love", xxx = "bad")
# in base R, you need can change the factor labels, but its clunky
Type_fct2 <- Type
levels(Type_fct2)[levels(Type_fct2) %in% c("love", "bad")] <- "xxx"
# methods using character vectors
Type_chr1 <- ifelse(as.character(Type) %in% c("love", "bad"), "xxx", as.character(Type))
Type_chr2 <- case_when(
Type %in% c("love", "bad") ~ "xxx",
Type == "none" ~ "something_else", # thrown in to show how to use `case_when` with many different criterion.
TRUE ~ NA_character_
)
})
库(用于猫)
图书馆(dplyr)
df如果您使用的是data.table,您可以执行以下操作:df[在%c中键入%s('love','bad),键入:='xxx']
library(forcats)
library(dplyr)
df <- within(df, { # if you use `dplyr`, you can replace this with mutate. You'd also need to change `<-` to `=` and add `,` at the end of each line.
Type_fct1 <- fct_recode(Type, xxx = "love", xxx = "bad")
# in base R, you need can change the factor labels, but its clunky
Type_fct2 <- Type
levels(Type_fct2)[levels(Type_fct2) %in% c("love", "bad")] <- "xxx"
# methods using character vectors
Type_chr1 <- ifelse(as.character(Type) %in% c("love", "bad"), "xxx", as.character(Type))
Type_chr2 <- case_when(
Type %in% c("love", "bad") ~ "xxx",
Type == "none" ~ "something_else", # thrown in to show how to use `case_when` with many different criterion.
TRUE ~ NA_character_
)
})