2017-03-04 47 views
0

我有一个包含缺失值的数据框。这些缺失的值跨越多个变量,但是在所述变量中出现,一次出现在特定观察值上。例如,我的数据帧看起来像:根据字符串的子集有条件地填充缺失值

r1 = c('', 'abc def', '') 
r2 = c('1', 'ghi jkl', '2') 
r3 = c('', 'mno pqr', '') 
df = as.data.frame(rbind(r1, r2, r3)) 

我想在所有情况下,“X”,填补双双失踪值,其中DF $ V2包含“高清”,请在两个缺失值与“Y” df $ V2包含'pqr'的所有情况,并且保留df $ V2包含'jkl'的所有行。换句话说,我想用一个数据帧,看起来像落得:

V1 V2  V3 
r1 x abc def  x 
r2 1 ghi jkl  2 
r3 y mno pqr  y 

我可以写一个函数基于文本的一个子集有条件填补空白单元格在一行中的多个列该行中的字符变量的值?非常感谢您的帮助。

回答

2

这是一个函数,它将输入数据框,更改值的列和要匹配的列作为输入。我还包括两个更多的可选参数来捕获模式(在你的案例中,def代表x,pqr代表y)。注意,我忽略了第三个模式,它保留了原来的值,假设其他的东西都保持不变。如果需要,可以修改该函数以接受更多模式。

功能

f1 <- function(df, cols, match_with, to_x = 'def', to_y = 'pqr'){ 
    df[cols] <- lapply(df[cols], function(i) 
    ifelse(grepl(to_x, match_with, fixed = TRUE), 'x', 
      ifelse(grepl(to_y, match_with, fixed = TRUE), 'y', i))) 
    return(df) 
} 

应用

#make sure your columns are characters and NOT factors 
df[] <- lapply(df, as.character) 

#apply the function 
f1(df, cols = c('V1', 'V3'), match_with = df$V2) 
# V1  V2 V3 
#r1 x abc def x 
#r2 1 ghi jkl 2 
#r3 y mno pqr y 
0

dplyr解决方案,使用case_when & the new .data. pronoun

library(dplyr) 
r1 = c('', 'abc def', '') 
r2 = c('1', 'ghi jkl', '2') 
r3 = c('', 'mno pqr', '') 
df = as.data.frame(rbind(r1, r2, r3), stringsAsFactors = FALSE) 

df %>% 
    mutate_at(
    c("V1", "V3"), 
    funs(case_when(
     grepl("def", .data$V2) ~ "x", 
     grepl("pqr", .data$V2) ~ "y", 
     TRUE ~ . 
    )) 
) 

请注意,您需要将开发版本dplyr关闭GH才能做到这一点。