我的数据如下所示:
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
谢谢!
答案 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"