[R] Recoding a variable
jim holtman
jholtman at gmail.com
Thu Jul 3 21:28:04 CEST 2008
Here is an example of a way to do it:
> x <- sample(LETTERS[1:5], 20, TRUE)
> x
[1] "D" "E" "A" "B" "A" "E" "A" "E" "A" "E" "C" "D" "A" "E" "D" "E"
"A" "C" "B" "B"
> # new vector with "D" and "E" = 0
> new.x <- ifelse((x == "D") | (x == "E"), 0, 1)
> cbind(x,new.x)
x new.x
[1,] "D" "0"
[2,] "E" "0"
[3,] "A" "1"
[4,] "B" "1"
[5,] "A" "1"
[6,] "E" "0"
[7,] "A" "1"
[8,] "E" "0"
[9,] "A" "1"
[10,] "E" "0"
[11,] "C" "1"
[12,] "D" "0"
[13,] "A" "1"
[14,] "E" "0"
[15,] "D" "0"
[16,] "E" "0"
[17,] "A" "1"
[18,] "C" "1"
[19,] "B" "1"
[20,] "B" "1"
>
>
>
On Thu, Jul 3, 2008 at 2:57 PM, Spencer <zhuge99 at u.washington.edu> wrote:
> Hi All,
>
> I'm relatively new to R. I have a variable, "internet use," which ranges
> from "Almost everyday, "Several times a week," "Several times a month,"
> "Seldom," "Never," and "Don't know." I want to recode this data into a new
> variable, say "use.internet," such that I have a dichotomous variable
> indicating simply whether or not they have access to the internet. Hence, I
> want to make "Never" and "Don't know" equal to 0, everything else 1. I
> thought about doing an if...then statement, but am not sure how to do this
> in R. This is easy to do in SPSS.
>
> A sample of the existing array is the following:
>
> Seldom Several times a week
> Several times a month
> Never
> Never Never Seldom
> Several times a week
> Never Never Almost everyday Never
> And the ideal new variable:
>
> 1
> 1
> 1
> 0
> 0
> 0
> 1
> 1
> 0
> 0
> 1
> 0
>
> Any help would be great!
>
> --
> Spencer Cohen
> PhD Student
> Department of Geography
> University of Washington
> Email: zhuge99 at u.washington.edu
> Website: staff.washington.edu/zhuge99
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
>
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem you are trying to solve?
More information about the R-help
mailing list