根据R中另一列的部分字符串值替换一列中的空白值

时间:2018-01-22 18:27:34

标签: r dataframe

我的数据如下所示:

pig<-data.frame(a=c("","","","","","Type1"),b=c("T1 NR","T2 NR","T2","T3","T3","Type1"))
print(pig)
  a      b
       T1 NR
       T2 NR
       T2
       T3
       T3
Type1  Type 1

如果a有时会为空白,但b始终具有与a中缺少的信息相对应的信息。我正在寻找两件事。首先,在b中存在“NR”的情况下,我希望“NR”出现在a中。第二,如果b中没有“NR”而a是空白,我想在“DKT”中出现一些其他字符串,以获得如下内容:

cow<-data.frame(a=c("NR","NR","DKT","DKT","DKT","Type1"),b=c("T1 NR","T2 NR","T2","T3","T3","Type1"))
print(cow)
 a     b
NR   T1 NR
NR   T2 NR
DKT   T2
DKT   T3
DKT   T3
Type1 Type1

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用data.frame

分配行/列子集
# You're doing string editing, so let's avoid factors from the start
pig <- data.frame(
  a = c("","","","","","Type1"),
  b = c("T1 NR","T2 NR","T2","T3","T3","Type1"),
  stringsAsFactors = FALSE
)

# The actual solution
has_nr <- grepl("NR", pig$b)
pig[has_nr, "a"] <- "NR"
pig[!has_nr & pig$a == "", "a"] <- "DKT"