Home > Mobile >  Reconstruct the content of a dataframe in R
Reconstruct the content of a dataframe in R

Time:10-07

I have a very simple question. I know there is a command in R to "reconstruct" a given dataframe. In this way, if (for instance) I directly constructed a dataframe in R I can avoid sending all the lines of code, or if I constructed the dataframe subsetting from other dataframes I can avoid sending all the files. For instance, for a dataframe like this:

year<-as.data.frame(c(1900:1905))
name<-as.data.frame(LETTERS[1:6])
sex<-as.data.frame(rep(c("M","F"),3))
example_df<-as.data.frame(bind_cols(year,name,sex))
colnames(example_df)<-c("year","name","sex")

the command_i_am_searching_for would give me the structure, in the form of example_df<-c(c(1900_1905),LETTERS[1:6])...and so on

I cannot find this command anywhere. Do you know which command it is?

CodePudding user response:

You can use dput:

dput(head(iris))
#> structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5, 5.4), 
#>     Sepal.Width = c(3.5, 3, 3.2, 3.1, 3.6, 3.9), Petal.Length = c(1.4, 
#>     1.4, 1.3, 1.5, 1.4, 1.7), Petal.Width = c(0.2, 0.2, 0.2, 
#>     0.2, 0.2, 0.4), Species = structure(c(1L, 1L, 1L, 1L, 1L, 
#>     1L), .Label = c("setosa", "versicolor", "virginica"), class = "factor")), row.names = c(NA, 
#> 6L), class = "data.frame")

Created on 2021-10-06 by the reprex package (v2.0.1)

CodePudding user response:

I think you just need data.frame.

example_df2 <- data.frame(
  year = c(1900:1905),
  name = LETTERS[1:6],
  sex = rep(c("M","F"),3)
)

Edit, apologies, I see what you want now, will delete this answer shortly as yep dput is the one

CodePudding user response:

The data.frame() base function can build a multi-column dataframe in a single statement. Eg:

mydf = data.frame(
col1=1:10,
col2=letters[1:10],
col3=rep('hello',10),
stringsAsFactors=FALSE
)

The last argument is to prevent strings from getting interpreted as factors (remove it if you're ok with factors)

  •  Tags:  
  • r
  • Related