gpt4 book ai didi

重新排序数据透视表

转载 作者:行者123 更新时间:2023-12-04 10:14:53 25 4
gpt4 key购买 nike

我有以下数据框:

df <- structure(list(rows = c(1, 2, 3, 4, 5, 6), col1 = c(122, 111, 
111, 222, 212, 122), col2 = c(10101, 20202, 200022, 10201, 20022,
22222), col3 = c(11, 22, 22, 22, 11, 22)), class = "data.frame", row.names = c(NA,
-6L))

rows col1 col2 col3
1 1 122 10101 11
2 2 111 20202 22
3 3 111 200022 22
4 4 222 10201 22
5 5 212 20022 11
6 6 122 22222 22

我想过滤至少 2,3,4 列之一包含“1”和“2”的行。

期望的结果是:

  rows col1  col2 col3
1 1 122 10101 11
4 4 222 10201 22
5 5 212 20022 11
6 6 122 22222 22


以下两个不起作用,因为它们一起扫描所有三列,而不是一一扫描。
df[which(apply(df[,2:4],1,function(x) any(grepl("1",x)) & any(grepl("2",x)))),]

或者
library(tidyverse)
TRIPS2_fin %>% filter_at(vars(2,3,4), any_vars(str_detect(., pattern="1|2")))

最佳答案

你可以使用:

df[apply(df[2:4], 1, function(x) any(grepl('1.*2|2.*1', x))),]

# rows col1 col2 col3
#1 1 122 10101 11
#4 4 222 10201 22
#5 5 212 20022 11
#6 6 122 22222 22

和类似使用 filter_at
library(dplyr)
df %>% filter_at(2:4, any_vars(grepl('1.*2|2.*1', .)))

关于重新排序数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61115606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com