使用 R 将错误的值移至右列

问题描述 投票:0回答:1

我有一个名为 Brand_ID 的列,其中 ID 的范围应该是 0-6,但在我的 Brand_ID 列中记录了一些 User_ID 数字。我一直无法找到将这些数字移动到右列的方法。

以下是数据示例:

                Brand_ID             User_ID
1060                   0 1515915625212799232
1061                   1 1515915625193362688
1062                   0 1515915625193362688
1063 1515915625216376320                  NA
1064 1515915625216376320                  NA
1065 1515915625216376320                  NA
1066 1515915625216376320                  NA
1067                   1 1313987370474800128
1068                   0 1313987370474800128
1069                   0 1515915625193362688
1070                   0 1515915625061714688

dput()

structure(list(Brand_ID = c(0, 1, 0, 1515915625216376320, 1515915625216376320, 
1515915625216376320, 1515915625216376320, 1, 0, 0, 0), User_ID = c(1515915625212799232, 
1515915625193362688, 1515915625193362688, NA, NA, NA, NA, 1313987370474800128, 
1313987370474800128, 1515915625193362688, 1515915625061714688
)), row.names = 1060:1070, class = "data.frame")

我尝试了以下代码来检查是否能够循环遍历 Brand_ID 列中的 User_ID 值,但没有打印任何内容。我也尝试过使用返回并粘贴而不是打印,但没有成功。

我还没有达到尝试实际切换值的目的,但我也迷失了如何做到这一点。

如有任何帮助,我们将不胜感激!

 brand <- !is.na(j$Brand_ID)
> for (x in 1:length(brand)){
+   if (brand[x] > 6)
+     {print(x)}
+   else
+     {next}
+ }
r data-analysis data-cleaning
1个回答
0
投票

这样的东西应该有效。 我也得到了科学记数法,因此有选项(scipen = 999)。

options(scipen = 999)
library(dplyr)
brand_fixed <- brand %>%
  mutate(User_ID = case_when(Brand_ID > 6 ~ Brand_ID,
                             Brand_ID <= 6 ~ User_ID)) %>%
           mutate(Brand_ID = case_when(Brand_ID > 6 ~ NA,
                                       Brand_ID <= 6 ~ Brand_ID))

这个想法是 mutate 通过使用 case_when 来评估是插入 Brand_ID 的当前值还是使用已经存在的 User_ID 来覆盖每一列。

希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.