【问题标题】:How to label large amount of data points using for loop in r?如何在r中使用for循环标记大量数据点?
【发布时间】:2020-04-21 04:26:48
【问题描述】:

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

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 和 Place 3。最后,我想要一个数据结构如下:

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 个唯一地址,我正在寻找可以循环并标记从 Place 1 到 Place 3000 的所有 3000 个地址的代码。

【问题讨论】:

  • 你能用 R 代码发布一个你的数据集的小例子吗?您可以按照本文stackoverflow.com/a/49995752/11437205 中的描述使用 dput()
  • 欢迎您! ID 和地址是在单独的列中还是在单个列中?
  • @Mohanasundaram,是的,ID 和地址在单独的列中

标签: r loops label


【解决方案1】:

我们可以使用matchunique 将唯一地址替换为"Place" + 后缀值,为每个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))

【讨论】:

  • 如何从这个输出中将答案导出到 CSV 文件?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-01
  • 2016-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-03
相关资源
最近更新 更多