Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a R data frame by row

Tags:

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

like image 550
Krowar Avatar asked Sep 30 '16 05:09

Krowar


1 Answers

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))
like image 127
Sandipan Dey Avatar answered Sep 26 '22 16:09

Sandipan Dey