首页 > 解决方案 > 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

标签: rgsub

解决方案


我确信有更好的方法,但这很有效并且很简单。对于每组替换,您可以运行单独的sub操作(gsub不是必需的,因为每个值只有一个匹配项)。对于每个替换集,您可以使用交替模式,如替换为 的项目water,或使用字符串中的规则,例如forest要替换为的集合中forest的重复,以及其中一个grasslandfarming集合中的重复您要替换的值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")
)

推荐阅读