[英]Rename df values using R
I have a dataframe as following : 我有一个如下数据框:
df <- data.frame(month = c("mazda miata 2017", "honda civic 2017"),
april = c(.1,.2),
may = c(.1,.2))
month april may
1 miata 0.1 0.1
2 civic 0.2 0.2
I would like to rename mazda 3
as mazda
and honda civic
as honda
. 我想将mazda 3
重命名为mazda
,将honda civic
重命名为honda
。 How can this be done using dplyr 如何使用dplyr完成
Since you mention dplyr
既然您提到dplyr
library(dplyr)
library(tidyr)
df%>%tidyr::separate(month, c("month","Drop"), " ")%>%select(-Drop)
month april may
1 mazda 0.1 0.1
2 honda 0.2 0.2
Do you need to use dplyr? 您需要使用dplyr吗?
Easy enough with gsub: 使用gsub足够简单:
df$month <- gsub("honda civic", "honda", df$month)
You can use the following solution to solve your problem: 您可以使用以下解决方案来解决您的问题:
levels(df$month)[levels(df$month )=="mazda 3"] <- "mazda"
levels(df$month)[levels(df$month )=="honda civic"] <- "honda"
Try a simple regular expression with str_replace
. 尝试使用str_replace
一个简单的正则表达式。
In the example below, replace "mazda " and "honda" with anything else you'd like to eliminate. 在下面的示例中,将“ mazda”和“ honda”替换为您要消除的其他任何内容。 Separate with the OR symbol |
用“或”符号分隔|
: :
df %>%
mutate(month = str_replace(month, "mazda |honda ", "") )
month april may
1 miata 2017 0.1 0.1
2 civic 2017 0.2 0.2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.