r - 基于相同的公司名称标准化客户 ID
问题描述
我需要使用众多客户 ID 之一,并将其标准化为所有完全相同的公司名称。
前
Customer.Ids Company Location
1211 Lightz New York
1325 Comput.Inc Seattle
1756 Lightz California
后
Customer.Ids Company Location
1211 Lightz New York
1325 Comput.Inc Seattle
1211 Lightz California
两家公司的客户 ID 现在相同。哪个代码最适合这个?
解决方案
我们可以match
在这里使用它,因为它返回第一个匹配的位置。我们可以match
Company
用Company
. 根据?match
match 返回其第二个参数的第一个参数的(第一个)匹配位置的向量。
df$Customer.Ids <- df$Customer.Ids[match(df$Company, df$Company)]
df
# Customer.Ids Company Location
#1 1211 Lightz NewYork
#2 1325 Comput.Inc Seattle
#3 1211 Lightz California
在哪里
match(df$Company, df$Company) #returns
#[1] 1 2 1
其他一些选项,使用sapply
df$Customer.Ids <- df$Customer.Ids[sapply(df$Company, function(x)
which.max(x == df$Company))]
在这里,我们遍历每个Company
并获取它发生的第一个实例。
或者使用ave
与@Shree 遵循相同逻辑的另一个选项,以按组获得第一次出现。
with(df, ave(Customer.Ids, Company, FUN = function(x) head(x, 1)))
#[1] 1211 1325 1211
推荐阅读
- wordpress - 如何根据插件版本、主题开发WordPress添加条件?
- reactjs - 在网站的 reactjs 代码中,我可以看到很多未使用的 js/css,但是如何将其反向映射到源代码文件以实际更改代码?
- chatbot - 无法从 Botium 导出 github 上的测试集
- c++ - 这是一个字谜程序,我正在检查两个相同长度的字符串是否相互字谜
- javascript - 如何在选择选项中输入值
- java - 我的 ArrayList 中的数据重复了数组最后输入的数据。这是什么原因?
- parsing - 具有 void * 类型的柠檬解析器标记值
- python - 如何在 Python 中按升序对第一个变量、按自定义顺序对第二个变量和按降序对第三个变量进行排序
- java - 无法在 SD 卡上创建新文件夹以备份许多文件
- c++ - 查找可以由保留字符顺序的第一个和第二个字符串的所有字符形成的给定字符串的所有交错