1

In R program, the list length is unknow.It is generated from for loop. for example:

ls <- list()
ls[[1]] <- 5
ls[[3]] <- a
ls[[6]] <- 8
....

Some index(ordinal number) is undefined.

I want to convert to data frame, such as follows:

1  5
2  NA
3  a
4  NA
5  NA
6  8
...

Additional question: how to get the ordinal number range of this list?

1 Answer 1

1

A base R approach could be, assuming here you have "ls" is already there in the environment :

Explanation: We first iterate through all all the elements using lapply, In the anonymous function part, we try to find the null values, where ever there is null value found , we replace with NA. Once the list NULL values are replaced with NA, we bind them row wise using 'rbind' from do.call. To get the last part as sequence, we can use either seq function or colon operator to create a sequence.

 dfs <- data.frame(col1 = do.call('rbind', lapply(ls, 
                      function(x)ifelse(is.null(x), NA, x))), 
                              col2 = seq(1,length(ls)), stringsAsFactors = F)

Alternate Using unlist(instead of do.call and rbind) :

dfs <- data.frame(col1 = unlist(lapply(ls, 
                function(x)ifelse(is.null(x), NA, x))), col2 = 
                        seq(1,length(ls)), stringsAsFactors = F)

Output:

    > dfs
   #   col1 col2
   # 1    3    1
   # 2   NA    2
   # 3    6    3
   # 4   NA    4
   # 5   NA    5
   # 6    8    6
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.