使用部分匹配重命名数据框列名称

时间:2020-05-27 19:08:39

标签: r

如果帖子底部有代码,如何使用df2第一列的部分匹配将df1的列名称替换为df2的第二列?输出应类似于df3。除了.length(即CS1.1.width,CS2.12.height等)之外,我的数据帧的整个字段都填充了许多其他名称,但CS#。#却充满了其他名称。始终保留在名称中。

然后我需要从名称中删除“ .length”。

我已经尝试在下面的问题的第一部分中使用pmatch,但是输出不正确。

names(df1) <- df2$new[pmatch(names(df1), df2$partial_atch)]

我将如何处理?谢谢。

old <- c("CS1.1.length", "CS1.7.length", "CS1.10.length", "CS1.12.length", "CS2.4.length", "CS2.6.length", "CS2.9.length", "CS2.11.length", "CS1.1.height")
df1 <- data.frame()
for (k in old) df1[[k]] <- as.character()


new <- c("Bob", "Alex", "Gary", "Taylor", "Tom", "John", "Pat", "Mary")
partial_match <- c("CS1.1", "CS1.7", "CS1.10", "CS1.12", "CS2.4", "CS2.6", "CS2.9", "CS2.11")
df2 <- data.frame(Partial_Match = partial_match, Name = new)


new1 <- c("Bob.length", "Alex.length", "Gary.length", "Taylor.length", "Tom.length", "John.length", "Pat.length", "Mary.length", "Bob.height")
df3 <- data.frame()
for (k in new) df3[[k]] <- as.character()

编辑:df1中的列数大于partial_match中的元素数,因此在df1中添加了另一列作为示例。

1 个答案:

答案 0 :(得分:0)

var startingList = new [] { new Thing { TruckNumber = 1 }, new Thing { TruckNumber = 2 }, new Thing { TruckNumber = 2 }, new Thing { TruckNumber = 3 }, new Thing { TruckNumber = 4 }, new Thing { TruckNumber = 5 }, new Thing { TruckNumber = 5 }, new Thing { TruckNumber = 6 }, new Thing { TruckNumber = 7 } } var cleanedList = new List<Thing>(); var duplicates = new List<Thing>(); foreach (var thing in startingList) { if (cleanedList.Any(t => t.TruckNumber == thing.TruckNumber)) { duplicates.Add(thing); } else { cleanedList.Add(thing); } } var lastTruckNumber = cleanedList.Select(t => t.TruckNumber).Max(); foreach (var thing in duplicates) { var nextTruckNumber = lastTruckNumber + 1; thing.TruckNumber = nextTruckNumber; lastTruckNumber = nextTruckNumber; } return cleanedList; 包中的str_replace选项如下:

之所以可行,是因为您可以使用向量stringi来替换为匹配的pattern =

我们需要在replacement =的末尾paste,因为这会阻止.取代CS1.1CS1.11

CS1.10