Arno Moonens
Arno Moonens

Reputation: 1213

Combine 2 elements out of a named list in R

I would like to take 2 elements out of a named list, apply a function to it, and put it in a matrix with as row and column name the name of respectively the first and second element that is combined. For example, I have this named list:

input <- list(a="tom", b="dick", c="harry")

And as the function to combine the elements, I would use paste0 The result of the matrix would then be:

  a         b           c          
a NA    "tomdick"   "tomharry" 
b NA       NA       "dickharry"         
c NA       NA          NA

I have already tried combn, but then I get:

> combn(input, 2, FUN=function(x) paste0(x[1], x[2]))
[1] "tomdick"   "tomharry"  "dickharry"

How can I do this?

Upvotes: 0

Views: 75

Answers (2)

Roman
Roman

Reputation: 17648

There must be a better way. But you can do something like this.

Create an empty dataframe:

d <- data.frame(matrix(NA, nrow = length(input), ncol = length(input)))
colnames(d) <- rownames(d) <- names(input)
d
   a  b  c
a NA NA NA
b NA NA NA
c NA NA NA

for loop to fill in the names:

for(i in row.names(d)){
for(j in colnames(d)){
d[i, j] <- paste0(input[i], input[j])
}}

Replace the names in the lower part of the Matrix with NAs

d[lower.tri(d, diag = T)] <- NA
d
     a       b         c
a <NA> tomdick  tomharry
b <NA>    <NA> dickharry
c <NA>    <NA>      <NA>

Upvotes: 2

lmo
lmo

Reputation: 38500

Combining @David Arenburg's comment with @Jimbou's answer,

input <- list(a="tom", b="dick", c="harry")
result <- outer(input, input, paste0)
result[lower.tri(result,diag = T)] <- NA

The name result stores the matrix that you posted.

Upvotes: 1

Related Questions