根据名称中的模式更新列对 [英] Update pairs of columns based on pattern in their names

查看:123
本文介绍了根据名称中的模式更新列对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的数据框:

col_1 <- c(1,2,NA,4,5)
temp_col_1 <-c(12,2,2,3,4)
col_2 <- c(1,23,423,NA,23)
temp_col_2 <-c(1,2,23,4,5)

df_test<-data.frame(col_1,temp_col_1,col_2, temp_col_2)

col_1 列中,我想用<$ c中的相应值替换 NA $ c> temp_col_1 并对 col_2 temp_col_2

In column col_1 I would like to replace NA with corresponding value from temp_col_1 and do the same for col_2 and temp_col_2

我知道如何使用 ifelse 语句手动完成,问题是我有大量的模式 col_name 和 temp_col_name 我想知道如何自动化它。

I know how to do it manually with ifelse statement, the problem is that I have tons of columns with pattern col_name and temp_col_name and I wonder how I can automate it.

我试过不同的东西,如 df_test [,粘贴('temp _','col_1 ]',但没有任何效果。
有什么建议吗?

I tried different things like df_test[,paste('temp_','col_1]', but nothing worked. Any suggestions?

推荐答案

# list of columns we need to check for NA's
col.to.check <- colnames(df_test)[!grepl("^temp", colnames(df_test))]
# these columns need not be checked
col.to.keep <- colnames(df_test)[grepl("^temp", colnames(df_test))]

func <- function(x){ 
  y <- which(is.na(df_test[[x]]))       # which position do NA's exist
  z <- df_test[[paste0("temp_", x)]][y] # which to be used to replace
  df_test[[x]][y] = z                   # replace them
  return(df_test[[x]])
  }

df = data.frame(lapply(col.to.check, func))
colnames(df) = col.to.check
cbind(df, df_test[col.to.keep])

#  col_1 col_2 temp_col_1 temp_col_2
#1     1     1         12          1
#2     2    23          2          2
#3     2   423          2         23
#4     4     4          3          4
#5     5    23          4          5

这篇关于根据名称中的模式更新列对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆