[R] shrink list by mathed entries
Soeren.Vogel at eawag.ch
Soeren.Vogel at eawag.ch
Sat Nov 14 10:30:43 CET 2009
On 14.11.2009, at 03:58, David Winsemius wrote:
> On Nov 13, 2009, at 11:19 AM, Soeren.Vogel at eawag.ch wrote:
>
>> a <- c("Mama", "Papa", "Papa; Mama", "", "Sammy; Mama; Papa")
>> a <- strsplit(a, "; ")
>> mama <- rep(F, length(a))
>> mama[sapply(a, function(x) { sum(x=="Mama") }, simplify=T) > 0] <- T
[...]
>> ... produces the variables "mama" and "papa" correctly. But how do
>> I remove all "Mama" list entries
[...]
> Maybe you should explain what you were trying to do? Perhaps:
>
> > a[!mama]
[...]
> I would sidestep that confusing sequence of logical assignments and
> just do this:
>
> > a[ -grep("Mama", a) ]
[...]
Explanation of what I want to do: This code is PHP, maybe rather crude
but it works the way I want it and explains my goal:
#!/usr/bin/php
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', false);
$strings = array("Mama", "Papa", "Papa; Mama", "", "Sammy; Mama;
Papa", "Josh", "Mama");
$vars = array("Mama", "Papa", "Sammy");
$i=0;
foreach($strings as $line){
$line = explode("; ", $line);
$matches = array_intersect($line, $vars);
$diffs = array_diff($line, $vars);
foreach($matches as $match){
eval("\$$match"."["."$i"."] = 1;"); // no easier way
}
foreach($diffs as $diff){
$others[$i] = $diff;
}
$i++;
}
print_r($Mama); // array with elements 0, 2, 4, and 6 set to "1"
print_r($Papa); // array with elements 1, 2, and 4, set to "1"
print_r($Sammy); // array with element 4 set to "1"
print_r($others); // array with elements 3 set to "", and 5 set to
"Josh"
?>
Sören
More information about the R-help
mailing list