How to create an R file line by line

In the exercise, I need to create such a data frame:

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 the data frame based on these columns.

What if I have the following vectors and would like to create the same data frame? Is there any way?

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

thank

+4
source share
2 answers

Try the following:

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 variables, you can optionally perform 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))
+3
source

Here is an option using transposeandmget

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
0
source

Source: https://habr.com/ru/post/1656307/


All Articles