[R] How to add specific column to data.set?

David Winsemius dwinsemius at comcast.net
Tue Apr 17 20:46:56 CEST 2012


On Apr 17, 2012, at 1:55 PM, R. Michael Weylandt wrote:

> Reproducible example not provided... try this -- it should generalize
> to multiple columns:
>
> EU <- c("UK","FR","DE") # Yes, I know there are more....
> countries <- data.frame( country1 = c("US","CH","UK","AU"), country2 =
> c( "CA", "MX", "FR", "DE"), stringsAsFactors = FALSE)
>
> cbind(countries, EU.Membership = Reduce(`&`, lapply(countries,
> function(x) x %in% EU)))
>

I would have thought this to be somewhat clearer:

countries$bothEU <- (countries$country1 %in% EU) & (countries$country2  
%in% EU)

And, yes, I know the parens weren't actually needed.

> Michael
>
> On Tue, Apr 17, 2012 at 1:24 PM, phillip03  
> <phillipbrigham at hotmail.com> wrote:
>> Hi Michael
>>
>> Sorry it is a data frame where to of the columns are 22 countries  
>> arranged
>> in random. I now want to add and ekstra column that is 1 if the  
>> country par
>> for the specific row is both european countries and 0 if not.
>>
>> Regards

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list