create a large list of different lengths of type integer and extract the id and values into a dataframe in r

To create a large list of different lengths of type integer and extract the id and values into a dataframe in R, you can use the following code:

main.r
# Create a list of different lengths of type integer
set.seed(123)
list_of_ints <- lapply(1:10, function(x) sample(1:100, size = x))

# Create a dataframe with id and values
df <- data.frame(
  id = rep(1:length(list_of_ints), sapply(list_of_ints, length)),
  value = unlist(list_of_ints)
)

# Print the dataframe
print(df)
324 chars
13 lines

In this code:

  1. We first create a list of integers of different lengths using lapply and sample.
  2. Then we create a dataframe with two columns: id and value.
  3. The id column is created by repeating the indices of the list (from 1 to the length of the list) as many times as the length of the corresponding integer vector.
  4. The value column is created by unlisting the list of integers.
  5. Finally, we print the dataframe.

The resulting dataframe will have two columns: id and value, where id is the index of the original list and value is the corresponding integer value.

This code can be used to create dataframes from lists of different lengths and types, not just integers.

Please note that this code requires the base package in R, which is installed by default.

related categories

gistlibby LogSnag