【发布时间】:2021-04-20 13:01:43
【问题描述】:
看起来是个很简单的问题,但目前我还没有找到任何解决方案。
考虑以下数据框:
dat <- data.frame(id=LETTERS[1:5],
land.use=c(3,4,9,34,39))
我需要用字符串替换land.use 列中的数字。问题是:我对数字 3、4 和 34 有不同的字符串。
但是,R 坚持将34 替换为3 和4 的串联字符串。
例如:
dat$land.use <- gsub("3","Bare soil", dat$land.use)
dat$land.use <- gsub("4","Primary Forest", dat$land.use)
dat$land.use <- gsub("9","Secondary Forest", dat$land.use)
dat$land.use <- gsub("34","Wheat", dat$land.use)
dat$land.use <- gsub("39","Soybean", dat$land.use)
> dat
id land.use
1 A Bare soil # This is OK
2 B Primary Forest # This is OK
3 C Secondary Forest # This is OK
4 D Bare soilPrimary Forest # This should be Wheat
5 E Bare soilSecondary Forest # This should be Soybean
我做错了什么?
【问题讨论】: