[英]How to label specific data points on a PCA plot in r using ggplot
[英]How to label large amount of data points using for loop in r?
我有一个数据集,其中包含ID
和与ID
关联的Address
。 一个例子是:
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。 我想将 label 分别作为 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 个唯一地址,我正在寻找可以循环的代码和 label 从 Place 1 到 Place 3000 的所有 3000 个地址。
我们可以使用match
和unique
将唯一地址替换为"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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.