[R] Data alignment

jim holtman jholtman at gmail.com
Sat Dec 3 13:15:34 CET 2011


try this:

> match(x$Name> x <- read.table(text = "Name - Value
+ A - 400
+ A - 300
+ B - 200
+ B - 350
+ C - 500
+ C - 350
+ D - 450
+ D - 600
+ E - 700
+ E - 750
+ F - 630
+ F - 650", header = TRUE, as.is = TRUE)
> map <- data.frame(key =   c("A", "B", "C", "D", "E", "F")
+                 , value = c( 1,   1,   2,   2,   3,   3)
+                 , stringsAsFactors = FALSE
+                 )
> x$ID <- map$value[match(x$Name, map$key)]
> x
   Name X. Value ID
1     A  -   400  1
2     A  -   300  1
3     B  -   200  1
4     B  -   350  1
5     C  -   500  2
6     C  -   350  2
7     D  -   450  2
8     D  -   600  2
9     E  -   700  3
10    E  -   750  3
11    F  -   630  3
12    F  -   650  3


On Sat, Dec 3, 2011 at 7:06 AM, Sarah Goslee <sarah.goslee at gmail.com> wrote:
> I doubt your data frame looks like that, with all the -, but regardless you
> can use ifelse() to construct your column.
>
> Sarah
>
> On Saturday, December 3, 2011, syrvn <mentor_ at gmx.net> wrote:
>> Hello!
>>
>> I have a data.frame which looks like:
>>
>> Name - Value
>> A - 400
>> A - 300
>> B - 200
>> B - 350
>> C - 500
>> C - 350
>> D - 450
>> D - 600
>> E - 700
>> E - 750
>> F - 630
>> F - 650
>>
>> I want to add another column where all A,B should get an index 1, all C,D
> an
>> index of 2 and all E,F an index of 3 so that the data.frame looks like:
>>
>> ID - Name - Value
>> 1 - A - 400
>> 1 - A - 300
>> 1 - B - 200
>> 1 - B - 350
>> 2 - C - 500
>> 2 - C - 350
>> 2 - D - 450
>> 2 - D - 600
>> 3 - E - 700
>> 3 - E - 750
>> 3 - F - 630
>> 3 - F - 650
>>
>> My data.frame is quite big so I cannot add all values by hand.
>>
>>
>> Cheers
>>
>>
>>
>>
>> --
>> View this message in context:
> http://r.789695.n4.nabble.com/Data-alignment-tp4153024p4153024.html
>> Sent from the R help mailing list archive at Nabble.com.
>>
>> ______________________________________________
>> 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.
>>
>
> --
> Sarah Goslee
> http://www.stringpage.com
> http://www.sarahgoslee.com
> http://www.functionaldiversity.org
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.



More information about the R-help mailing list