[R] modify a data frame by values in the columns

Peter Ehlers ehlers at ucalgary.ca
Sat Jun 4 20:19:39 CEST 2011


On 2011-06-04 11:11, Peter Ehlers wrote:
> On 2011-06-03 13:34, Jason024 wrote:
>> I have a data frame like this:
>>
>>       col1 col2
>> r1     2    1
>> r2     4    3
>> r3     6    5
>> r4     8    7
>> r5    10    9
>> r6    12   11
>> r7    14   13
>> r8    16   15
>> r9    18   17
>> r10   20   19
>>
>> I want to modify this data frame, for example, assign every row in column
>> col1 and col2 to -1 if the values in col1 is less than 12 and values in col2
>> is greater than 10. The result should look like this:
>>       col1 col2
>> r1     -1    1
>> r2     -1    3
>> r3     -1    5
>> r4     -1    7
>> r5     -1    9
>> r6    12   -1
>> r7    14   -1
>> r8    16   -1
>> r9    18   -1
>> r10  20   -1
>>
>> I have been struggling to make it to work. Any help is appreciated!
>
> This seems made for within(); calling your data.frame 'd':
>
>    d.new<- within(d, {
>                        col1<- ifelse(col1<  12, -1, col1)
>                        col2<- ifelse(col2>  10, -1, col2)
>                       })

And, of course, the ifelse() isn't necessary:

   d.new <- within(d, {
                       col1[ col1 < 12 ] <- -1
                       col2[ col2 > 10 ] <- -1
                      })


Peter Ehlers

>>
>> Jason
>>
>>
>> --
>> View this message in context: http://r.789695.n4.nabble.com/modify-a-data-frame-by-values-in-the-columns-tp3571995p3571995.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.
>
> ______________________________________________
> 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.



More information about the R-help mailing list