简体   繁体   中英

Changing column value based on part of a string in another column in R

I'm new to R so please bear with me! I Have a dataframe named 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'. 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. 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
      )
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM