该旗行基于条件创建新列

时间:2019-01-31 04:51:55

标签: r mutate

我试图过滤此数据帧称为df

structure(list(ï..ID = structure(c(2L, 1L, 4L, 6L, 3L, 7L, 5L, 
8L), .Label = c("Jay ", "Jim", "Jim ", "John ", "Mike ", "Peter", 
"Peter ", "Tom"), class = "factor"), Target1 = structure(c(8L, 
4L, 6L, 5L, 2L, 1L, 3L, 7L), .Label = c("Andreas", "Cheyne", 
"Frank", "John", "Mickey", "Raj", "Sarah", "Timothy"), class = "factor"), 
    Target2 = structure(c(4L, 3L, 1L, 5L, 2L, 1L, 1L, 1L), .Label = c("", 
    "Jake", "Peter", "Timothy ", "Tommy "), class = "factor"), 
    Parter1 = structure(c(3L, 2L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("", 
    "Mike ", "Timothy"), class = "factor"), Parter2 = structure(c(1L, 
    2L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("", "Peter"), class = "factor")), class = "data.frame", row.names = c(NA, 
-8L))

我正在尝试过滤数据框,以使如果出现在此向量x

中的名称
x=c("Raj", "Timothy")

在第2-5列中出现2次以上,该行将有一个名为flag的全新列的变量,如果名称出现2次以上,则标志= 1,如果名称出现2次以上,则标志= 0出现不超过2次。

1 个答案:

答案 0 :(得分:1)

在Base R中,我们可以将applyMARGIN = 1一起使用(行式)

df$flag <- as.integer(apply(df, 1, function(row) sum(row %in% x)) > 2)

df
#  ï..ID Target1 Target2 Parter1 Parter2 flag
#1   Jim Timothy Timothy Timothy            1
#2   Jay    John   Peter    Mike   Peter    0
#3  John     Raj                            0
#4 Peter  Mickey   Tommy                    0
#5   Jim  Cheyne    Jake                    0
#6 Peter Andreas                            0
#7  Mike   Frank                            0
#8   Tom   Sarah                            0

apply将数据帧转换为矩阵,并且可能会变慢一些时间。您可以使用具有相同逻辑的apply来避免sapply调用

df$flag <- as.integer(sapply(1:nrow(df), function(i) sum(df[i, ] %in% x)) > 2)

另一种编写方式

df$flag <- as.integer(colSums(sapply(1:nrow(df), function(i) df[i, ] %in% x)) > 2)

PS-名称中有一些空格,我必须先运行

df[] <- lapply(df, trimws)

删除它们。