6

In an exercise, I have to create a data frame like this :

Name <- c("Sam","Frank","Amy")
Age <- c(22,25,26)
Weight <- c(150,165,120)
Sex <- c("M", "M", "F")
df <- data.frame (row.names = Name, Age, Weight, Sex) 

So basically I create the columns and then a data frame based on these columns.

What if I have the following vectors and I'd like to create the same data frame ? Is there a way ?

Sam <- c(22,150, 'M')
Frank <- c(25, 165, 'M')
Amy <- c(26, 120, 'F')

Thanks

Krowar
  • 341
  • 2
  • 7
  • 15
  • 1
    Problem: `c(22, 150, 'M')` will convert the numbers into strings: a vector can only be one "class" of data, so `logical < integer < numeric < character`. Though not base R, there is however [`frame_data`](https://blog.rstudio.org/2016/03/24/tibble-1-0-0/) which allows a row-wise view of creating the data.frame (though not in the specific way you suggest). – r2evans Sep 30 '16 at 05:53
  • Does this answer your question? [Creating an R dataframe row-by-row](https://stackoverflow.com/questions/3642535/creating-an-r-dataframe-row-by-row) – Jan Aug 28 '22 at 13:41

2 Answers2

3

Try this:

df <- as.data.frame(rbind(Sam, Frank, Amy), stringsAsFactors = FALSE)
names(df) <- c('Age' , 'weight', 'Sex')

df
      Age Weight Sex
Sam    22    150   M
Frank  25    165   M
Amy    26    120   F

If you are concerned about the type of the variables you may additionally do the conversion:

df$Age <- as.integer(df$Age)
df$weight <- as.integer(df$weight)
df$Sex <- as.factor(df$Sex)

Or we can use type.convert:

df <- data.frame(lapply(df, type.convert))
zx8754
  • 52,746
  • 12
  • 114
  • 209
Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63
  • Can you include the output of `str(df)`? My guess is that it will not be what is intended (`Age` and `Weight` will be factors, not numbers). – r2evans Sep 30 '16 at 05:56
  • I see what you are saying, updated, this should work – Sandipan Dey Sep 30 '16 at 06:00
  • Since stringsAsFactors=FALSE was done, this variable was character (and not factor), now if we want it as factor then we need to coerce it to factor. – Sandipan Dey Sep 30 '16 at 06:08
  • Sorry, didn't catch that change from your first version. You are correct. (Can't say I've *ever* had need to convert something to a factor, so I'm spring-loaded against them.) – r2evans Sep 30 '16 at 06:09
0

Here is an option using transpose and mget

nm1 <- c("Sam", "Frank", "Amy")
`row.names<-`(data.frame(setNames(lapply(data.table::transpose(mget(nm1)), 
          type.convert), c("Age", "Weight", "Sex"))), nm1)
        Age Weight Sex
# Sam    22    150   M
# Frank  25    165   M
# Amy    26    120   F
akrun
  • 874,273
  • 37
  • 540
  • 662