循环遍历多列以根据条件生成新变量
Looping over multiple columns to generate a new variable based on a condition
我正在尝试根据多列中的值生成一个新列(变量)。
我在数据集中有超过 60 列,我想对要循环的列进行子集化。
我在条件中使用的所有字符的列变量,当匹配特定模式时,return新变量中的值为 1。
我正在使用 when 因为我需要 运行 每列上的多个条件以 return 一个值。
代码:
df read.csv("sample.csv")
*#Generate new variable name*
df$new_var <- 0
*#For loop through columns 16 to 45*
for (i in colnames(df[16:45])) {
df <- df %>%
mutate(new_var=
case_when(
grepl("I8501", df[[i]]) ~ 1
))
}
这不起作用,因为当我 table 结果时,我只得到 1 个值匹配。
我的另一个尝试是使用:
for (i in colnames(df[16:45])) {
df <- df %>%
mutate(new_var=
case_when(
df[[i]] == "I8501" ~ 1
))
}
还有其他可能的方法 运行 通过具有多个条件的多个列并相应地更改变量的值吗?使用 R 实现 ?
如果我理解你想要什么,我认为你只需要在 case_when()
中指定另一种情况,以便在事情不匹配时保留现有值 "I8501"
。我会这样做:
df$new_var <- 0
for (index in (16:45)) {
df <- df %>%
mutate(
new_var = case_when(
grepl("I8501", df[[index]]) ~ 1,
TRUE ~ df$new_var
)
)
}
我认为更好的方法是使用有用的 apply()
:
has_match = apply(df[, 16:45], 1, function(x) sum(grepl("I8501", x)) > 0)
df$new_var = ifelse(has_match, 1, 0)
请检查这是否适用于您的文件。
样本 df:
df <- data.frame(C1=c('A','B','C','D'),C2=c(1,7,3,4),C3=c(5,6,7,8))
> df
C1 C2 C3
1 A 1 5
2 B 7 6
3 C 3 7
4 D 4 8
library(dplyr)
df %>%
rowwise() %>%
mutate(new_var = as.numeric(any(str_detect(c_across(2:last_col()), "7")))) # change the 2:last_col() to select your column range ex: 2:5
在任意列中查找“7”的输出:
C1 C2 C3 new_var
<chr> <dbl> <dbl> <dbl>
1 A 1 5 0
2 B 7 6 1
3 C 3 7 1
4 D 4 8 0
我正在尝试根据多列中的值生成一个新列(变量)。 我在数据集中有超过 60 列,我想对要循环的列进行子集化。
我在条件中使用的所有字符的列变量,当匹配特定模式时,return新变量中的值为 1。
我正在使用 when 因为我需要 运行 每列上的多个条件以 return 一个值。
代码:
df read.csv("sample.csv")
*#Generate new variable name*
df$new_var <- 0
*#For loop through columns 16 to 45*
for (i in colnames(df[16:45])) {
df <- df %>%
mutate(new_var=
case_when(
grepl("I8501", df[[i]]) ~ 1
))
}
这不起作用,因为当我 table 结果时,我只得到 1 个值匹配。
我的另一个尝试是使用:
for (i in colnames(df[16:45])) {
df <- df %>%
mutate(new_var=
case_when(
df[[i]] == "I8501" ~ 1
))
}
还有其他可能的方法 运行 通过具有多个条件的多个列并相应地更改变量的值吗?使用 R 实现 ?
如果我理解你想要什么,我认为你只需要在 case_when()
中指定另一种情况,以便在事情不匹配时保留现有值 "I8501"
。我会这样做:
df$new_var <- 0
for (index in (16:45)) {
df <- df %>%
mutate(
new_var = case_when(
grepl("I8501", df[[index]]) ~ 1,
TRUE ~ df$new_var
)
)
}
我认为更好的方法是使用有用的 apply()
:
has_match = apply(df[, 16:45], 1, function(x) sum(grepl("I8501", x)) > 0)
df$new_var = ifelse(has_match, 1, 0)
请检查这是否适用于您的文件。
样本 df:
df <- data.frame(C1=c('A','B','C','D'),C2=c(1,7,3,4),C3=c(5,6,7,8))
> df
C1 C2 C3
1 A 1 5
2 B 7 6
3 C 3 7
4 D 4 8
library(dplyr)
df %>%
rowwise() %>%
mutate(new_var = as.numeric(any(str_detect(c_across(2:last_col()), "7")))) # change the 2:last_col() to select your column range ex: 2:5
在任意列中查找“7”的输出:
C1 C2 C3 new_var
<chr> <dbl> <dbl> <dbl>
1 A 1 5 0
2 B 7 6 1
3 C 3 7 1
4 D 4 8 0