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
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))
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