replace ALL... if the first...

#1

i have a dataframe like :


subj  Gender	    act
 101   Male      801-walking forward
 101   Male      802-walking backward
 205   Female    909 back-sitting
 208   Male      914 right-recovery

I would like to replace the values ​​starting with "8 ..." with "0" and those starting with "9 .." with "1"

in this case

subj  Gender	    act
 101   Male          0
 101   Male          0
 205   Female        1
 208   Male          1

I thought with something like "case_when" or "str_replace" or "mutate" ... but I can not write a regular expression to say this.

0 Likes

#2

Again, please ask your questions with a reproducible example or at least some sample data on a copy/paste friendly format.

2 Likes

#3

sorry, i think reproducibile example is the "dataframe" that i have put.

so...
the dataframe is:

subj  Gender	    act
 101   Male      801-walking forward
 101   Male      802-walking backward
 205   Female    909 back-sitting
 208   Male      914 right-recovery

if i write a code like:

dataframe$act <- str_replace_all(dataframe$act, "^8", "0")

dataframe becomes

subj  Gender	    act
 101   Male      001-walking forward
 101   Male      002-walking backward
 205   Female    009 back-sitting
 208   Male      014 right-recovery

only the first number ( 8 or 9) is replaced with 0

dataframe$act<- case_when(dataframe$act== "^8" ~ "0", dataframe$act=="^9" ~ "1")

the columns dataframe$act becomes all NA..

0 Likes

#4

Have you read the link I gave you? That is not reproducible because I can't just copy your code paste it on my rstudio session and reproduce your issue.

0 Likes

#5

I'm sorry ... I do not want to be disrespectful, it's that I'm not very practical with either the system or the language. tell me, is that ok?

df <- data.frame(subject= c("101","102","103"), gender = c("male","male","male"), act = c("801-sadsa", "802-dasdas", "905-dsad"))
View(df)

df$act<- case_when(df$act== "^8" ~ "0", df$act=="^9" ~ "1")

df$act <- str_replace_all(df$act, "^8", "0")

0 Likes

#7

It's better but not OK jet, because you forgot to include the calls to the libraries that you are using, take a look at the way I'm sharing the solution.

library(stringr)
library(dplyr)

df <- data.frame(subject= c("101","102","103"),
                 gender = c("male","male","male"),
                 act = c("801-sadsa", "802-dasdas", "905-dsad")
)

args <- c("^8.*" = "0",
          "^9.*" = "1")

df %>% 
    mutate(act = str_replace_all(act, args))
#>   subject gender act
#> 1     101   male   0
#> 2     102   male   0
#> 3     103   male   1

Created on 2019-02-17 by the reprex package (v0.2.1)

1 Like

#8

ok, thanks...I will try to be more and more precise.

0 Likes

closed #9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.

0 Likes