Jon_Gendron
Jon_Gendron

Reputation: 23

Applying each element of a vector to corresponding dataframe rows in parallel

I have a data frame where the first 3 columns are tag names for the last column, which is a list of matrices. Each of the matrices are binary (only 1's and 0). I would like to pull one of the tag names from each row and replace all values of 1 in the row's matrix with that tag name, but I want to avoid using a loop so that I can do this for all rows in parallel.

Example Dataframe:

> df1
   name scenario       Fire
1 name1   scene1 1, 1, 1, 0
2 name2   scene2 0, 1, 0, 1
3 name3   scene3 0, 0, 0, 1

> class(df1$Fire)
[1] "list"

> df1$Fire
[[1]]
     [,1] [,2]
[1,]    1    1
[2,]    1    0

[[2]]
     [,1] [,2]
[1,]    0    0
[2,]    1    1

[[3]]
     [,1] [,2]
[1,]    0    0
[2,]    0    1

The target format would look something like this ...

> df1$Fire
[[1]]
     [,1]     [,2]    
[1,] "scene1" "scene1"
[2,] "scene1" "0"     

[[2]]
     [,1]     [,2]    
[1,] "0"      "0"     
[2,] "scene2" "scene2"

[[3]]
     [,1] [,2]    
[1,] "0"  "0"     
[2,] "0"  "scene"

I have tried using apply(df1,1,function) approach, without success because the resulting output is in a list format rather than gaining the original structure of the df1. Any thoughts?

Upvotes: 0

Views: 84

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389265

You can use Map :

df1$Fire <- Map(function(x, y) replace(x, x == 1, y), df1$Fire, df1$scenario)
df1$Fire

#[[1]]
#     [,1]     [,2]    
#[1,] "scene1" "scene1"
#[2,] "scene1" "0"     

#[[2]]
#     [,1]     [,2]    
#[1,] "0"      "0"     
#[2,] "scene2" "scene2"

#[[3]]
#     [,1] [,2]    
#[1,] "0"  "0"     
#[2,] "0"  "scene3"

data

Usually it is better if you add data in a reproducble form using dput so that we don't have to construct it from scratch.

df1 <- structure(list(name = c("name1", "name2", "name3"), scenario = c("scene1",
"scene2", "scene3"), Fire = list(structure(c(1, 1, 1, 0), .Dim = c(2L, 
2L)), structure(c(0, 1, 0, 1),.Dim = c(2L, 2L)), structure(c(0, 
0, 0, 1),.Dim = c(2L, 2L)))),row.names = c("1", "2", "3"),class = "data.frame")

Upvotes: 1

Related Questions