Home > Software engineering >  If values in two columns satisfy two different conditions, store corresponding value of third column
If values in two columns satisfy two different conditions, store corresponding value of third column

Time:12-06

I have a data frame that looks like this:

col1   col2    col3    y
1      2       2       10
0      1       0       15
2      2       1       17
1      2       1       9
2      0       0       8
0      1       2       21

I want to store the value in y in a list if col1 and col2 meet two separate conditions.

In this example my conditions are if if the value in col1 == 0 and the value in col2 == 1, then store the value of y in the list.

col3 is completely ignored. I just added it in here because my actual dataframe has many columns that I am not interested in.

So, in this example, the result would be a list of length 2 with the values "15" and "21" inside.

CodePudding user response:

library(dplyr)


data <-
  data.frame(
    col1 = c(1,0,2,0),
    col2 = c(2,1,2,1),
    y = c(10,15,17,21)
  )

data %>% 
  filter(col1 == 0 & col2 == 1) %>% 
  pull(y) %>% 
  as.list()

CodePudding user response:

Here's an example from yours without using dplyr. You can use the subset function.

# Create a sample data frame
df = data.frame(col1 = c(1,0,2,1,2,0),
                col2 = c(2,1,2,2,0,1),
                col3 = c(2,0,1,1,0,2),
                y = c(10,15,17,9,8,21))

# Use the subset() function to extract rows where col1 == 0 and col2 == 1
filtered_df = subset(df, col1 == 0 & col2 == 1)

# Extract the values of column "y" from the filtered data frame
y_values = filtered_df$y

# Print the y_values
print(y_values)

You can also use the [ operator

# Use the [ operator to extract rows where col1 == 0 and col2 == 1
filtered_df = df[df$col1 == 0 & df$col2 == 1,]

CodePudding user response:

You can use select(y) as.list(). The pull method will give you a list for each value of y. If you want a single list that has all the values, you can use select.

data <-
        data.frame(
            col1 = c(1,0,2,0),
            col2 = c(2,1,2,1),
            y = c(10,15,17,21)
        )

data %>% 
    filter(col1 == 0 & col2 == 1) %>% 
    select(y)%>% as.list()
  • Related