r - gsub() 对具有多个替换的数据框中的所有值
问题描述
我有一个大型数据框,其中包含指示数千个位置(Land_Use)随时间推移(从 1972 年到 2020 年每年)的土地使用情况的字符串。有 23 个土地利用字符串(在我的数据框中定义为因素),我想将它们简化为 3 个。我在另一个数据框(简单)中匹配了这些简化,我目前没有在代码中使用,但我觉得就像我可以通过某种方式使其更有效率。
例如,我想用一个名为“water”的字符串替换所有土地利用字符串“lake”、“ocean”、“river”、“pond”。所有的土地利用字符串都写着“原生森林”、“外来森林”……,一个字符串叫做“森林”。以及所有的土地使用字符串,上面写着“养猪”、“异国草原”、“奶牛养殖”……只有一个字符串叫做“牧场”
我已经使用 gsub 和 lapply 进行了各种尝试,但我无法让它工作。
我将如何做到这一点,是否有一种有效的方法可以一次在整个数据帧上执行此操作,或者我是否需要逐列进行,并按土地使用进行土地使用?
Land_Use <- read.csv("Data\\Land_Use.csv")
Simple <- read.csv("Data\\Land_Use_simplified_classes.csv")
Land_Use <- gsub('native forest','forest.',Land_Use$1972) # the replacement works but my dataframe become a vector containing only data from 1972
lapply(Land_Use, function(y) gsub("native forest", "forest", y)) # something very weird happened - I think it has converted to a list, not sure if the replacement worked
解决方案
我确信有更好的方法,但这很有效并且很简单。对于每组替换,您可以运行单独的sub
操作(gsub
不是必需的,因为每个值只有一个匹配项)。对于每个替换集,您可以使用交替模式,如替换为 的项目water
,或使用字符串中的规则,例如forest
要替换为的集合中forest
的重复,以及其中一个grassland
或farming
集合中的重复您要替换的值pasture
:
df[] <- lapply(df, function(x) sub("\\b(lake|ocean|river|pond)\\b", "water", x))
df[] <- lapply(df, function(x) sub(".*(forest)", "\\1", x)) # also: sub(".*(forest)", "forest", x)
df[] <- lapply(df, function(x) sub(".*(farming|grassland)", "pasture", x))
结果:
df
x y z
1 water forest pasture
2 water forest pasture
3 water forest pasture
4 water forest pasture
5 forest water forest
6 forest water water
7 pasture water water
数据:
df <- data.frame(
x = c("lake", "ocean", "river", "pond","native forest", "exotic forest", "diary farming"),
y = c("native forest", "exotic forest", "native forest", "exotic forest","lake", "ocean", "river"),
z = c("pig farming", "exotic grassland", "diary farming", "exotic grassland","exotic forest","lake", "ocean")
)
推荐阅读
- aws-lambda - Lambda - 将源 IP 传递给自定义授权方
- azure-devops - 在 Azure Devops 中复制发布管道所有阶段的更改
- c# - Net Core:查找Entity Framework Core和Reflection的主键
- sqlite - SQLite instr(...) 不区分大小写的查询
- java - java.lang.NullPointerException 调用模型类的函数
- java - 字符串数组在 for 循环中初始化时忽略索引 0
- javascript - 使用 dropzone laravel 通过电子邮件发送多张图片
- php - 如何使用 PHP 将 https 错误状态设置为 404,以便它可以由 .htaccess 文件处理?
- python-3.x - 将我的代码从多处理更改为正常
- python - TypeError:无法处理此数据类型