[R] How to replace strings in data frames by condition

Jim Lemon drjimlemon at gmail.com
Sat Sep 19 01:34:49 CEST 2015


Hi Robert,
In your example, all of the numeric values are single digit. If this is the
case in the real data, I think this will do:

# assume edf is the name of the data frame
levels(edf$q_1_SQ009)<-c(levels(edf$q_1_SQ009),"0")
edf$q_1_SQ009[is.na(edf$q_1_SQ009)]<-"0"
get_first_char<-function(x) return(unlist(strsplit(as.character(x),""))[1])
edf$q_1_SQ009<-sapply(sapply(edf$q_1_SQ009,get_first_char),as.numeric)

Jim


On Sat, Sep 19, 2015 at 4:55 AM, sakko <sakko.saul at gmx.de> wrote:

> Hi,
> this is my first post in this forum and I am new to Ra. I am desperately
> seeking for help.
>
> There is a data frame given in which I want to replace some values like
> following:
>
> Existing data frame:
>                    q_1_SQ009
> 1                              4
> 2                           <NA>
> 3                              3
> 4                              2
> 5   5: Stimme voll und ganz zu
> 6                              4
> 7                              4
> 8                              2
> 9   1: Stimme überhaupt nicht zu
>
> Wanted data frame:
>                        q_1_SQ009
> 1                              4
> 2                              0
> 3                              3
> 4                              2
> 5                              5
> 6                              4
> 7                              4
> 8                              2
> 9                              1
>
> This means that every "<NA>", "5: Stimme voll und ganz zu" and "1: Stimme
> überhaupt nicht zu" shall be replaced by 0, 5, 1
>
>
> I beg you all for any help.... please
>
> Many thanks in advance
>
>
>
> Robert
>
>
>
>
>
> --
> View this message in context:
> http://r.789695.n4.nabble.com/How-to-replace-strings-in-data-frames-by-condition-tp4712469.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

	[[alternative HTML version deleted]]



More information about the R-help mailing list