R 如果行值等于 colnames 赋值 1 否则赋值 0

R if row value equals colnames assign 1 else 0

原来table是这样的:

id food
1 fish
2 egg
2 apple

对于每个 id,食物的值应该为 1 或 0,因此 table 应该如下所示:

id food fish egg apple
1 fish 1 0 0
2 egg 0 1 0
2 apple 0 0 1

一个使用reshape2包的dcast()函数的命题:

df1 <- read.table(header = TRUE, text = "
id  food
1   fish
2   egg
2   apple
")

###

df2 <- reshape2::dcast(data = df1, 
                       formula = id+food ~ food, 
                       fun.aggregate = length, 
                       value.var = "food")
df2
#>   id  food apple egg fish
#> 1  1  fish     0   0    1
#> 2  2 apple     1   0    0
#> 3  2   egg     0   1    0

###

df3 <- reshape2::dcast(data = df1, 
                       formula = id+factor(food, levels=unique(food)) ~ 
                                   factor(food, levels=unique(food)), 
                       fun.aggregate = length, 
                       value.var = "food")
names(df3) <- c("id", "food", "fish", "egg", "apple")
df3
#>   id  food fish egg apple
#> 1  1  fish    1   0     0
#> 2  2   egg    0   1     0
#> 3  2 apple    0   0     1

# Created on 2021-01-29 by the reprex package (v0.3.0.9001)

此致,