-1

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!

  • You can use `list_df <- split(df[1:2], df$Result)`. If you need separate dataframes you can then add `list2env(list_df, .GlobalEnv)`. You can have a look here https://stackoverflow.com/questions/9713294/split-data-frame-based-on-levels-of-a-factor-into-new-data-frames – Ronak Shah May 03 '20 at 14:48
  • I need two different dataframes one that only contains the columns "StudyID" and "Score" results which are equal to "great" and one dataframe that contains the results which are equal to "bad" – Kestin Jones May 03 '20 at 14:52

1 Answers1

0

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?

efz
  • 425
  • 4
  • 9