[英]Changing column value based on part of a string in another column in R
I'm new to R so please bear with me! 我是R新手,请多多包涵! I Have a dataframe named
mydata
. 我有一个名为
mydata
的数据mydata
。 Here's a sample of the relevant columns: 以下是相关列的示例:
Backlog.Item.Type Description
Feature Assignment 1
Product Backlog Item As a user I want to
Task Do this
Now, what I want to accomplish is the following: if part of the string in Description
matches 'As a' or 'As an', I want to replace that rows value for the Backlog.Item.Type
column with the string 'User Story'. 现在,我要完成以下任务:如果
Description
中字符串的一部分与“ As a”或“ As an”匹配,我想用字符串“ User Story”替换Backlog.Item.Type
列的行值。 '。 To select these rows, I use 要选择这些行,我使用
x <- mydata[grepl("As a", mydata[["Description"]]) | grepl("As an", mydata[["Description"]]), ]
However, I do not know how to then replace the corresponding value in the Backlog.Item.Type
column. 但是,我不知道如何替换
Backlog.Item.Type
列中的相应值。 It is probably pretty simple to do this, but any help would be greatly appreciated! 这样做可能很简单,但是任何帮助将不胜感激! Thanks in advance, I hope I have been clear enough and formulated my question in an understandable manner!
在此先感谢您,我希望我已经足够清楚,并以可以理解的方式提出了我的问题!
I guess there will be a more elegant solution, nevertheless this will do the trick: 我想将会有一个更优雅的解决方案,尽管这样做会成功:
library(stringr)
df=tibble(Backlog=c("Feature","Product","Task"),Description=c("Assignment 1","As a user i want to","Do this"))
matches<-c("a user","an user")
matchTable=sapply(matches,function(x) str_detect(df$Description,x))
rows=sapply(1:nrow(df),function(x) any(matchTable[x,1],matchTable[x,2]))
df$Description[rows]='User Story'
library(stringr)
library(dplyr)
mydata %>%
mutate(
Backlog.Item.Type = case_when(
str_detect(mydata$description, "As a") | str_detect(mydata$description, "As an") ~ "User Story",
!(str_detect(mydata$description, "As a") | str_detect(mydata$description, "As an"))) ~ Backlog.Item.Type
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.