Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a data fram from lists

Tags:

list

dataframe

r

I have 3 lists and I would like to combine them into a dataframe, where each column is an element of a list.

There are the 3 lists (ld is a nummeric with value 112)

ld <- 112

# 3 lists
or <- as.list(rep(0, 8))
thetax <- lapply(0:7, function(x) ld * cos (x * pi / 4))
thetay <- lapply(0:7, function(x) ld * sin (x * pi / 4))

Here is my attempt to combine them into a data.frame

 df3 <- data.frame(or, thetax, thetay)

I think this should be very simple and basic but I can't do it.

I have been searching for the answer for hours this and have been trying different things but nothing seems to work so far, and I can't execute it.

like image 885
Devang Akotia Avatar asked Jul 05 '26 19:07

Devang Akotia


2 Answers

The fact that you can't create data.frames with list columns is a longstanding annoyance. In decreasing order of preference, you can either

  • Use data_frame from the tibble package instead.

    tibble::data_frame(or, thetax, thetay)
    
  • Create a list with dimensions, then convert that to be a data frame, as suggested by David Arenburg.

    data.frame(cbind(or, thetax, thetay))
    
  • Create the data frame, then add the list columns afterwards.

    df3 <- data.frame(1:8)[,FALSE]
    df3$or <- or
    df3$or <- thetax
    df3$or <- thetay
    
  • Use structure to make the data frame.

    structure(
      list(or, thetax, thetay), 
      class = "data.frame", 
      row.names = .set_row_names(8)
    )
    
like image 168
Richie Cotton Avatar answered Jul 08 '26 13:07

Richie Cotton


I may be missing something, but I would think this will work as vectors instead of lists. Does this work for you, or am I way off target?

x <- 0:7
ld <- 112
or <- rep(0, 8)
thetax <- ld * cos (x * pi / 4)
thetay <- ld * sin (x * pi / 4)
df3 <- data.frame( or, thetax, thetay )
like image 38
rosscova Avatar answered Jul 08 '26 13:07

rosscova