turn a list into a table in r

To turn a list into a table in R, we can use the data.frame function. Here's an example:

main.r
# create a list
my_list <- list(Name = c("Alice", "Bob", "Charlie"),
                Age = c(25, 30, 35),
                City = c("New York", "Los Angeles", "Chicago"))

# convert list to data frame
my_table <- data.frame(my_list)

# print the data frame
print(my_table)
272 chars
11 lines

This will output:

main.r
     Name Age         City
1   Alice  25     New York
2     Bob  30  Los Angeles
3 Charlie  35      Chicago
108 chars
5 lines

Note that in this example, each element of the list became a column in the resulting data frame. If the elements of the list do not have the same length, R will show a warning and recycle the values to make them the same length. To avoid this, it's important to ensure that all the elements of the list have the same length, or that they are of the same data type.

gistlibby LogSnag