r语言 - 子集基函数在输出时忽略重复条目



我最近问如何使用字典文件来重新编码数据集中的值(使用数据值(字典))。R)

我遇到了一个更简单的问题,但是这个修复不起作用。假设我有以下数据集,每行是一个地理单元,列V1列出了"第一个邻居"。,但使用行号列出它。:

V1 <- c(1, 2, 1)
id <- c(110001, 110002, 110003)
dataset <- as.data.frame(matrix(c(id, V1), ncol=2))
colnames(dataset) <- c("id", "V1")

因此在这个数据集上,区域110001是自身(V1 = 1)的邻居,区域110003是110001 (V1 = 1)的邻居。现在,不再将V1(第一个邻居)显示为"1, 2, 1",而是将其显示为地理区域"110001, 110002, 110001"id

我创建了一个字典包含地理区域行号和id的文件:

dictionary <- as.data.frame(matrix(c(dataset$id, 1:nrow(dataset)),ncol=2))
colnames(dictionary) <- c("id","row")

然后,我尝试使用突变来映射这些。请注意,我有许多邻近变量(V1-V30),并且在示例中只使用一个,因此我将使用转换为所有变量的语法:

new_dataset <- dataset %>% mutate(across(starts_with("V"), ~subset(dictionary, row == cur_column(), select= id)))     

这应该做的是:跨列运行,将值与字典中行处的值进行比较,然后返回适当的id。似乎问题是dataset$V1中的重复条目(在本例中,第1行和第3行等于"1")。如果我一行一行地继续,这将工作:

first_row <- dataset[1,] %>% mutate(V1 = subset(dictionary, row == V1, select= id))    
second_row <- dataset[2,] %>% mutate(V1 = subset(dictionary, row == V1, select= id))  
third_row <- dataset[3,] %>% mutate(V1 = subset(dictionary, row == V1, select= id))

我的印象是"子集"忽略重复项。例如,如果我运行这个:

subset(dictionary, row == dataset$V1, select= id)

它应该返回"110001, 110002, 110001",但只返回"110001, 110002"

关于如何使子集返回一切或另一种方法的任何想法?

我们可以使用rowwise

library(dplyr)
dataset %>%
rowwise %>% 
mutate(V1 = subset(dictionary, row == V1, select= id)$id) %>%
ungroup

-ouptut

# A tibble: 3 x 2
id     V1
<dbl>  <dbl>
1 110001 110001
2 110002 110002
3 110003 110001

data.table

library(data.table)
setDT(dataset)[dictionary, V1 := i.id, on = .(V1 = row)]
> dataset
id     V1
1: 110001 110001
2: 110002 110002
3: 110003 110001

如果有多个列,例如:'V1', 'V2'等

dataset$V2 <- V1[c(1, 3, 2)]
nm1 <- paste0("V", 1:2)
setDT(dataset)
for(nm in nm1) 
dataset[dictionary, (nm) := i.id, on = setNames("row", nm)][]

与产出

> dataset
id     V1     V2
1: 110001 110001 110001
2: 110002 110002 110001
3: 110003 110001 110002

可以对修改过的数据集使用自左连接:

library(dplyr)
dataset %>% 
left_join(
dataset %>% 
group_by(V1) %>% 
slice(1),
by = "V1") %>% 
select(-V1)

这返回

id.x   id.y
1 110001 110001
2 110002 110002
3 110003 110001

也许像下面这样的基础R选项?

transform(
dataset,
V1 = ave(id, V1, FUN = function(x) head(x, 1))
)

,

id     V1
1 110001 110001
2 110002 110002
3 110003 110001

最新更新