[R] transform data.frame holding answers --> data.frame holding logicals

Florent D. flodel at gmail.com
Fri Dec 2 04:59:01 CET 2011


I have this. I have modified your input structure to be a matrix. I
think it is generally recommended to use matrices over data.frames
when your data allows it, i.e., when you only have one type of data,
here character(). Matrices are easier to work with.
x <- matrix(  c('BMW', '', '',    'Mercedes', 'VW', '',    'Skoda',
'VW', 'BMW',    '', '', '',    'VW', 'Skoda', ''  ),  ncol=3,
dimnames=list(    paste('person', 1:5, sep=''),    paste( 'v', 1:3,
sep='' )  ))
brands <- sort(unique(array(x)))[-1]has.used <- t(apply(x, 1,
function(a, b){b %in% a}, brands))colnames(has.used) <- brandshas.used
On Thu, Dec 1, 2011 at 2:42 PM, Jean V Adams <jvadams at usgs.gov> wrote:
> saschaview wrote on 12/01/2011 12:30:18 PM:
>
>> Hello
>>
>> I have a data frame, x, holding 5 persons answering the question which
>> cars they have used:
>>
>> # the data frame
>> x <- as.data.frame(
>>    matrix(
>>      c('BMW', '', '',
>>        'Mercedes', 'VW', '',
>>        'Skoda', 'VW', 'BMW',
>>        '', '', '',
>>        'VW', 'Skoda', ''
>>      ),
>>      ncol=3,
>>      dimnames=list(
>>        NULL,
>>        paste( 'v', 1:3, sep='' )
>>      )
>>    )
>> )
>>
>> How do I transform this data frame to a data frame stating whether they
>> have used the presented car:
>>
>>     BMW  Mercedes  VW  Skoda
>> 1  T    F         F   F
>> 2  F    T         T   F
>> 3  T    F         T   T
>> 4  F    F         F   F
>> 5  F    F         T   T
>>
>> My idea was to first find all levels by:
>>
>> v <- unique(unlist(lapply(x, levels)))
>>
>> But then I am stuck.
>>
>> Thanks for help, *S*
>>
>> --
>> Sascha Vieweg, saschaview at gmail.com
>
>
> Try this:
>
> uniq.cars <- sort(unique(unlist(x)))
> y <- t(apply(x, 1, function(xrow) match(uniq.cars, unique(xrow))))
> dimnames(y)[[2]] <- uniq.cars
> y2 <- !is.na(y[, -1])
> y2
>
> Jean
>        [[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.



More information about the R-help mailing list