Skip to content

shrink list by mathed entries

3 messages · Soeren.Vogel at eawag.ch, David Winsemius

#
Hello

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
papa <- rep(F, length(a))
papa[sapply(a, function(x) { sum(x=="Papa") }, simplify=T) > 0] <- T
# ... more variables

... produces the variables "mama" and "papa" correctly. But how do I  
remove all "Mama" list entries in "a" in the same run, that is, shrink  
the list by what was already matched?

Thank you for your help!

S?ren Vogel
#
On Nov 13, 2009, at 11:19 AM, Soeren.Vogel at eawag.ch wrote:

            
Maybe you should explain what you were trying to do?  Perhaps:

 > a[!mama]
[[1]]
[1] "Papa"

[[2]]
character(0)

I would sidestep that confusing sequence of logical assignments and  
just do this:

 > a[ -grep("Mama", a) ]
[[1]]
[1] "Papa"

[[2]]
character(0)
#
On 14.11.2009, at 03:58, David Winsemius wrote:

            
[...]
[...]
[...]
[...]

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