如何在r中使用for循环标记大量数据点?

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

我有一个数据集,其中包含与ID关联的AddressID。一个例子是:

ID   Address
1001 123 E example rd, 12300
1001 123 E example rd, 12300
1001 456 W example rd, 45600
1002 789 N example rd, 78900
1002 123 E example rd, 12300
1003 789 N example rd, 78900
1004 456 W example rd, 45600
1004 789 N example rd, 78900
1004 789 N example rd, 78900
1004 123 E example rd, 12300

现在,在上面的示例中,我们有3个唯一ID。我想将它们分别标记为Place 1,Place 2和Place3。最后,我想具有如下数据结构:

ID     x1        x2        x3          x4 
1001   Place 1   Place 1   Place 2
1002   Place 3   Place 1
1003   Place 3
1004   Place 2   Place 3   Place 3     Place 1

因为在我的真实数据集中,我有大约3000个唯一地址,所以我正在寻找可以循环并标记从位置1到位置3000的所有3000个地址的代码。

r loops label
1个回答
1
投票

我们可以使用"Place"matchunique +后缀值替换唯一地址,为每个ID创建一个唯一索引,并使用pivot_wider获得宽格式的数据。

library(dplyr)

df1 <- df %>%
  mutate(Address = paste0('Place', match(Address, unique(Address)))) %>%
  group_by(ID) %>%
  mutate(row = paste0('x', row_number())) %>%
  tidyr::pivot_wider(names_from = row, values_from = Address)

df1

#    ID   x1     x2     x3     x4    
#  <int> <chr>  <chr>  <chr>  <chr> 
#1  1001 Place1 Place1 Place2 NA    
#2  1002 Place3 Place1 NA     NA    
#3  1003 Place3 NA     NA     NA    
#4  1004 Place2 Place3 Place3 Place1

要导出到csv,我们可以使用write.csv

write.csv(df1, 'newfile.csv', row.names = FALSE)

数据

df <- structure(list(ID = c(1001L, 1001L, 1001L, 1002L, 1002L, 1003L, 
1004L, 1004L, 1004L, 1004L), Address = structure(c(1L, 1L, 2L, 
3L, 1L, 3L, 2L, 3L, 3L, 1L), .Label = c("123 E example rd, 12300", 
"456 W example rd, 45600", "789 N example rd, 78900"), class = "factor")), 
class = "data.frame", row.names = c(NA, -10L))
© www.soinside.com 2019 - 2024. All rights reserved.