简体   繁体   中英

R- Dataframe making a new dataframe from a old one

All the code I used is below:

df <- data.frame("StudyID" = paste("Study", seq(1:100), sep = "_"),
             "Score" = sample(c(-15:30),100, replace = TRUE))


df$Result<- ifelse(df$Score > 20, "great",
                 ifelse(df$Score < -5, "bad", "neutral"))

I want to create a NEW dataframe1 that contains the "StudyID" and "Score" only for people who have a Result that is equal to "great". The resulting columns should only contain "StudyID"and "Score" and not the Result column.

Then I want to creat another NEW dataframe2 for the people who have a Result that is equal to "bad" with the columns "StudyID" and "Score".

Your help is really appreciated!

I would simply try

df1 <- df[df$Result=='great',1:2]
df2 <- df[df$Result=='bad',1:2]

so that:

head(df1)
    StudyID Score
9   Study_9    26
12 Study_12    30
13 Study_13    29
15 Study_15    22
19 Study_19    23
25 Study_25    21

and the same for df2 . does it help?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM