Sarvo
Sarvo

Reputation: 113

R Generate counts from vector with 0 for values that do not exist

My data is of the following form in R

data<-list(list(Name= "Value1",corresponding_set=c(1,2,3)), list(Name="AnotherKey",corresponding_set=c(4,5,3,4)))

What I am trying to obtain is data frame of format

            1 2 3 4 5
Key         1 1 1 0 0
AnotherKey  0 0 1 2 1 

I tried the following:

myfunc<-function(x){
  currValue<-x$corresponding_Set
  for(i in 1:5){
    print(c(i,sum(currValue==i))
  }
 }
sapply(data,myfunc)

The above code does print the value I need but in the following format

1 1
2 1
3 1
4 0
5 1
1 0
2 0
3 0
4 2
5 1

My questions is

  1. For the type of data used is the structure of "data" appropriate? if not how should it be designed. Currently this data is static and I would like to keep it this way for now
  2. I am not able to form an idea how to convert the vectors that I print to a grid format (data frame or matrix)

Any help appreciated!

Upvotes: 1

Views: 116

Answers (1)

Peter
Peter

Reputation: 7790

You can get the result you're looking for by converting the nested lists into data.frames, binding them together and then calling table.

data <- list(list(Name = "Value1",
                  corresponding_set = c(1, 2, 3)), 
             list(Name = "AnotherKey",
                  corresponding_set = c(4, 5, 3, 4)))

# Convert each list element to a data.frame
dfs <- lapply(data, as.data.frame)
dfs
# [[1]]
#     Name corresponding_set
# 1 Value1                 1
# 2 Value1                 2
# 3 Value1                 3
# 
# [[2]]
#         Name corresponding_set
# 1 AnotherKey                 4
# 2 AnotherKey                 5
# 3 AnotherKey                 3
# 4 AnotherKey                 4


# bind the two data.frames together 
df <- do.call(rbind, dfs)
df
#         Name corresponding_set
# 1     Value1                 1
# 2     Value1                 2
# 3     Value1                 3
# 4 AnotherKey                 4
# 5 AnotherKey                 5
# 6 AnotherKey                 3
# 7 AnotherKey                 4

# build a table
table(df)
#             corresponding_set
# Name         1 2 3 4 5
#   AnotherKey 0 0 1 2 1
#   Value1     1 1 1 0 0

Upvotes: 2

Related Questions