[R] Vector with factors inside lists/tuples

David Winsemius dwinsemius at comcast.net
Sat Jun 25 19:44:58 CEST 2011


On Jun 25, 2011, at 12:49 PM, Håvard Wahl Kongsgård wrote:

> Hi, this seems like a strange question, but in R is there a function  
> that
> can handle vectors containing factors inside lists/tuples?

Yes, A very strange question, indeed ... since dataframes are lists  
that commonly contain vectors of factors and you should have  
encountered them very early in your self-study of R. The number of  
functions that operate on dataframes is large. Are you very early in  
efforts at learning R? Have you read the Posting Guide? (You're still  
posting html format.)

?factor
?list
?dataframe

> Or is there some
> other approach/functions I can use?
> Like for example
>
> V1
> "{"Harry","Brown")"
> "{"Brown","Harry")"

Is that an example that would make sense in some other language?  
(Opening curly-brace and closing paren makes no sense in R or  for  
that matter in what small amount I know of set theory.) Since your  
example makes no sense, it remains possible that you're looking for  
set operations:

?union

>
> I want to use these variables in a machine learning setting, And  
> don't want
> to convert these into multiple vectors, given share number of factors.

Lists (of which dataframes are one specific example) are the usual  
method of handling structures of arbitrary structure (including  
factors). 'lapply' is the usual choice for repetitive application of a  
function to elements of lists. The is also 'rapply' for recursive  
application

 > lapply(list(factor(letters[1:10]), list(c(1:10), c(20:30) ),  
letters[10:20]), length)
[[1]]
[1] 10

[[2]]   # second element is a list with two members
[1] 2   # lapply() only works with the first 'level' of a list

[[3]]
[1] 11
 > rapply(list(factor(letters[1:10]), list(c(1:10), c(20:30) ),  
letters[10:20]), length)
[1] 10 10 11 11
 > lapply(list(factor(letters[1:10]), list(c(1:10), c(20:30) ),  
letters[10:20]), class)
[[1]]
[1] "factor"

[[2]]
[1] "list"

[[3]]
[1] "character"

-- 

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list