我有一个数据帧,看起来像这样:
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
如果col1
和col2
满足两个单独的条件,我想将y
中的值存储在一个列表中。
在这个例子中,我的条件是如果如果col1
中的值== 0并且col2
中的值== 1,那么将y
的值存储在列表中。
col3
被完全忽略。我只是在这里添加它,因为我的实际数据框架有许多我不感兴趣的列。
因此,在本例中,结果将是一个长度为2的列表,值为"15"one_answers"21";在里面。
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()
下面是一个不使用dplyr的示例。您可以使用子集函数
# 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)
也可以使用[
运算符
# Use the [ operator to extract rows where col1 == 0 and col2 == 1
filtered_df = df[df$col1 == 0 & df$col2 == 1,]
可以使用select(y) + as.list()。pull方法将为y的每个值提供一个列表。如果你想要一个包含所有值的列表,你可以使用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()