我有一个数据集,我需要将每个数据重命名为" KAS"对于列中的每个KASARAGOD实例。我需要将该列中的所有内容替换为" KAS"如果找到实例。
P O, PIN: 671543,KASARAGOD
只是KAS
我应该使用什么命令?
示例数据:
G05 G06 G07 G08 G09 G10 address_2
A A+ A+ A+ A+ A+ KUMBADAJE P O, PIN: 671551, KASARAGOD
A B B B+ A A MALLAM P O, PIN: 671542, KASARAGOD
B+ B B+ A+ C+ B+ KUMBADAJE P O, PIN: 671551, KASARAGOD
B+ B+ B B+ A A+ MOVVAR P O, PIN: 671543, KASARAGOD
B B B B+ A+ A+ MOVVAR P O, PIN: 671543, KASARAGOD
A+ A+ A+ A+ A+ A+ MOVVAR P O, PIN: 671543, KASARAGOD
B+ B+ B A B+ A YETHADKA P O, PIN: 671551, KASARAGOD
C C C C C A MOVVAR P O, PIN: 671543, KASARAGOD
A+ A+ A+ A+ A+ A+ MOVVAR P O, PIN: 671543, KASARAGOD
答案 0 :(得分:2)
示例数据:
x <- c("(P O, PIN: 671543,RANCHI)", "(P O, PIN: 671543,BLAH)", "(P O, PIN: 67338,RANCITY)", "(P O, PIN: 671543,BBBCHI)")
可以尝试grepl
和ifelse
x <- ifelse(grepl("RANCHI", x), "(RAN)", x)
x
## [1] "(RAN)" "(P O, PIN: 671543,BLAH)" "(P O, PIN: 67338,RANCITY)" "(P O, PIN: 671543,BBBCHI)"
或只是grep
(或grepl
)
x[grep("RANCHI", x)] <- "(RAN)"
x
## [1] "(RAN)" "(P O, PIN: 671543,BLAH)" "(P O, PIN: 67338,RANCITY)" "(P O, PIN: 671543,BBBCHI)"
答案 1 :(得分:2)
这会将包含在括号中的RANCHI
的每个文本实例替换为(RAN)
。
x <- gsub("\\(.*RANCHI.*\\)", "\\(RAN\\)", x)
答案 2 :(得分:1)
我的第一个想法是gsub。如果您的数据框名为edu,请尝试
edu$address_2 <- gsub(".*KASARAGOD.*", "KAS", edu$address_2)
这会给你
G05 G06 G07 G08 G09 G10 address_2
A A+ A+ A+ A+ A+ KAS
A B B B+ A A KAS
B+ B B+ A+ C+ B+ KAS
B+ B+ B B+ A A+ KAS
B B B B+ A+ A+ KAS
A+ A+ A+ A+ A+ A+ KAS
B+ B+ B A B+ A KAS
C C C C C A KAS
A+ A+ A+ A+ A+ A+ KAS