I'm trying to figure out how to add a data.frame or data.table to the first position in a list.
Ideally, I want a list structured as follows:
List of 4 $ :'data.frame': 1 obs. of 3 variables: ..$ a: num 2 ..$ b: num 1 ..$ c: num 3 $ d: num 4 $ e: num 5 $ f: num 6
Note the data.frame is an object within the structure of the list.
The problem is that I need to add the data frame to the list after the list has been created, and the data frame has to be the first element in the list. I'd like to do this using something simple like append
, but when I try:
append(list(1,2,3),data.frame(a=2,b=1,c=3),after=0)
I get a list structured:
str(append(list(1,2,3),data.frame(a=2,b=1,c=3),after=0)) List of 6 $ a: num 2 $ b: num 1 $ c: num 3 $ : num 1 $ : num 2 $ : num 3
It appears that R is coercing data.frame into a list when I'm trying to append
. How do I prevent it from doing so? Or what alternative method might there be for constructing this list, inserting the data.frame into the list in position 1, after the list's initial creation.
By using df. loc[index]=list you can append a list as a row to the DataFrame at a specified Index, In order to add at the end get the index of the last record using len(df) function.
Dataframe append syntaxYou type the name of the first dataframe, and then . append() to call the method. Then inside the parenthesis, you type the name of the second dataframe, which you want to append to the end of the first.
Pandas DataFrame can be converted into lists in multiple ways. Let's have a look at different ways of converting a DataFrame one by one. Method #1: Converting a DataFrame to List containing all the rows of a particular column: Python3.
The issue you are having is that to put a data frame anywhere into a list as a single list element, it must be wrapped with list()
. Let's have a look.
df <- data.frame(1, 2, 3) x <- as.list(1:3)
If we just wrap with c()
, which is what append()
is doing under the hood, we get
c(df) # $X1 # [1] 1 # # $X2 # [1] 2 # # $X3 # [1] 3
But if we wrap it in list()
we get the desired list element containing the data frame.
list(df) # [[1]] # X1 X2 X3 # 1 1 2 3
Therefore, since x
is already a list, we will need to use the following construct.
c(list(df), x) ## or append(x, list(df), 0) # [[1]] # X1 X2 X3 # 1 1 2 3 # # [[2]] # [1] 1 # # [[3]] # [1] 2 # # [[4]] # [1] 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With