检测数据帧中是否存在一组字母数字代码

问题描述 投票:0回答:1

我有一个数据框(标题:fy14y),其中包含 100 个变量(c1 - c100),其中包含不同长度的字母数字代码(例如 1-S023;2-Y0408)

创建一个二进制变量来检测以下列表中的一个或多个以下代码是否连续出现?

1-A400,1-A401,1-A402,1-A410,1-A415,1-A4152,1-A4158,1-B377,1-P360,1-P362,1-P364,1-U900

即0=如果它们都没有出现,1=如果一个或两个或三个等出现一次或多次。

我尝试过 stringr str_detect 函数,但运气不佳

谢谢!

r stringr
1个回答
0
投票

您可以尝试这个基本的 R 答案 -

# Please add all the codes that you want to check
codes_to_check <- c("1-A400","1-A401")
# Columns to check
cols <- paste0("c", 1:100)
df$result <- as.integer(Reduce(`|`, lapply(df[cols], `%in%`,codes_to_check)))
df
© www.soinside.com 2019 - 2024. All rights reserved.